How To Make Inheritance Work In JavaScript

How To Make Inheritance Work In JavaScript

Is Javascript an object-oriented language? If you are coming from a c++or Java background, you may have noticed that Javascript is in one way similar to those languages, and in the other way it is different from those languages.

I guess you are not alone. If you have learned classical class-based objected-oriented languages, you can get confused, especially, at beginning of learning OOP concepts in Javascript. In this post, I will help you escape that confusion

Let’s begin …

Javascript and Web Development

Most of us introduce to javascript when we learn to add interactivity to the web browser. We actually use Javascript without knowing what it really is. We learn events, then we might learn string manipulations, arrays, and even Javascript objects. Let’s be honest…we use Javascripts objects and functions without knowing how they work; or without knowing the underline mechanism. If you are from a c++ or Java background as I mentioned before, you might have to assume that Javascript works the same way that those languages work. But, I am sorry, You are wrong., mmm, maybe, not totally :).

Objects in Javascript

Except for primitive values or primitive types such as null, undefined, strings, numbers, BigInt, boolean, and symbols, EVERYTHING IN JAVASCRIPT IS AN OBJECT. I mean EVERYTHING: arrays, functions, constructors, etc. Even primitive types( except null and undefined ) have object equivalents (Primitive wrapper objects ).

How do Javascript objects different from that of C++/Java

Unlike class-based OOP languages, Javascript has no classes. In C++ or Java, you must create classes before you create an object. But, in Javascript object itself is the most important thing, and you can create other objects with the Object type.

Wait….Don’t tell lies….ES2015 has introduced classes.

Yes, Modern Javascript has classes, but they are actually functions. ( sorry…I am not going to talk about this much further as it is out of the scope of this post. I will have another post on class in JS later)

let’s discuss more on objects…

An object is a collection of related data ( properties) and/or functionality ( methods). These properties and methods are organized as key-value pairs. The value can be a property ( number, array, another object) or a method that does an action on the data held in properties(‘data properties’).

const objectName = { key: value };

This kind of object is called object literal, which is different from objects based on classes introduced in ES2015.

Now that you have a basic understanding of objects, let’s discuss a very critical property in every Javascript object.

The Prototype property

The prototype is a built-in property in every javascript object. This property is used to implement inheritance in javascript. Inheritance is the OOP concept. In class-based OOP, it is the mechanism in which one class inherits the attributes and methods of another class. However, in javascript, this is somewhat different as it has no true classes. Inheritance in javascript is the mechanism in which the features of one object inherits from another object using Prototypes. This inheritance is called prototypal inheritance.

Create the following object in your browser’s console.

const myObject = { name: 'john’',
                   greet(){  console.log(`Hi ${this.name}`); }
                  }

Now, when you type myObject and add the period operator(.) right after it in the console, the browser should display all the available properties of the myObject.

image.png

Notice, carefully that other than “greet” and “name”, which are defined by you, there are many built-in hidden properties. Pay close attention to the __proto__ . This is the key to the prototype property that we are talking about.

To check the value of the __proto__, or otherwise, to access prototype property you can use Object.getPrototypeOf() method as follows

Object.getPrototypeOf(myObject);

{constructor: ƒ, defineGetter: ƒ, defineSetter: ƒ, hasOwnProperty: ƒ, lookupGetter: ƒ, …}

You can also access it if you enter myObject.__proto__ in the console.

An important thing to notice here is that the Prototype property itself is an Object. In other words, the value of the __proto__ is an Object.

Because a prototype is an Object, it also has its own prototype property. This goes like a chain until the value is null (__proto__: null)

Enter the following in the console

Object.getPrototypeOf( myObject.__proto__).

It should display null in the console.

This chain is called the prototype chain, and it provides the basis for prototypal inheritance in Javascript.

Setting prototype property

Now, let us see how we can use the prototype chain to our advantage.

Create the following object in the console.

const Animal = { group: 'mammal', noOfLegs:4 }
const Dog = { speak :'bark', color: 'black' }
Dog.__proto__ = Animal;

Now, we can access the properties of the Animal using the Dog object

Dog.group
Dog.noOfLegs

When you type Dog.group, javascript will first look for it in the Dog Object. Since it is not there, then it will automatically look at the prototype property of that Dog object, which is the Animal object, and display the relevant properties. This is how the prototypal chain and inheritance work in javascript.

if you check the prototype property of the Animal Object in the console with Object.getPrototypeOf(Dog), you notice the below.

{ group: ‘mammal’, noOfLegs: 4 }

Expand it to see more details

image.png

As you can see the [[Prototype]] property of the Animal object is hidden, and the value of it is an Object( javascript built-in Object )

You can expand it further until you reach __proto__: null, which is the end of the prototypal chain.

Summary

Object refers to a collection of properties in Javascript. While javascript is not a classical class-based OOP language, it implements OOP concepts such as inheritance using special property named prototype property. Chaining this property of relevant objects, javascript implements its own prototypal inheritance.