JavaScript — A Brush up on Prototypal Inheritance

Prototypal Inheritance is still a not much explored space in JavaScript by many developers and holds a important place in the learning curve of the language. This article will be a brush up on this space covering various topics on high level.

Topics to be covered:

  1. Prototype Delegation through New Keyword
  2. For in Loop with Prototype
  3. Static methods
  4. Instanceof Operator
  5. defineProperty
  6. OLOO (Object Linking to Other Objects)

1 — Prototype Chain:

Prototype chaining is used to build new types of objects based on existing ones. Constructor functions have a property called prototype. Adding properties and methods to the prototype property will automatically add the method or property to all objects created by the constructor function. These prototype method or properties are visible under __proto__ object found in every object.

Lets see an example of how to inherit properties using prototype chaining.

In the above example, we have create two objects namely a, b. Each of the above two objects has its own property and own prototype methods. Now we have used Object.setPrototypeOf method to replace prototype of object — ‘a’ with properties of object — ‘b’ along with its default prototype methods. Both properties from ‘a’ as well ‘b’ are retained in object ‘a’ and hence inheritance is achieved through prototype chaining.

2-Prototype Delegation through New Keyword:

  1. A new object is created out of the class
  2. Prototype is linked to the object
  3. ‘this’ binding for the instance is made.

Refer to the below example:

A class named Car is created. When it is instantiated using the new keyword, a new object is created (newCar), prototype is linked to the object (`__proto__`) and this.name is bound with “BMW”. This explains Prototypal delegation using new keyword

3- For in Loop with Prototype:

Lets examine through the following example:

Lets consider an object Foo, which has properties name, firstName and a prototype property lastName. When we run the for in loop through Foo, ideally we should get 2 iterations, but the image below proves that its 3 iterations including the prototype property.

We can still restrict for in loop from looping through prototype properties by having a check for hasOwnProperty as below:

Using HasOwnProperty

4- Static Methods:

In order to execute such methods directly, use Static keyword during declaration of the method and it does the magic as below:

To avoid making this post further longer, I am splitting it into two parts. The remaining four topics can be found here in the continuation.

Thanks for reading through pretty long article.

6+ years of Experience in React-Redux / NodeJS / GraphQL / TypeScript. https://vilvaathiban.com