1.

What is a fat arrow function in JavaScript?

Answer»

Prototypal inheritance is to ADD NEW capabilities to a constructor function using Prototype.
Let’s first understand what are Constructor functions. They are basically JavaScript way to implement the concept of Classes.
Let’s CONSIDER the example below, where we have a “Car” constructor function. In it we have a “model”, which we are also returning by getModel(). Now we can create a new instance of it by using the “new” keyword. Each instance will have its own “this” and have its own getModel(). 

let Car = function(model) {   this.model = model;   this.getModel = function() {     return this.model;   } }   let harryCar = new Car('toyota'); console.log(harryCar.getModel()); //toyota   let maryCar = new Car('nissan');

console.log(maryCar.getModel()); //nissan

Now, the problem is that every time we create a new instance we get a new COPY of getModel(). Suppose we have 100 instances, then we will have 100 copies. Below console log shows the same thing.

We should somehow move the logic for getModel() outside our Constructor function and that is where the concept of Prototype helps.

In JavaScript as you know everything is an Object. Whenever a function is created there are two object ONE is the function object another is the prototype object. Now to access the Prototype object we have a property on the function object also known as “prototype”.

Every instance created from the function have access to the Prototype object.  Now, let’s move our getModel() outside our Constructor function using prototype.

let Car = function(model) {   this.model = model; }   Car.prototype.getModel = function() {     return this.model;  }   let harryCar = new Car('toyota'); console.log(harryCar.getModel()); //toyota   let maryCar = new Car('nissan'); console.log(maryCar.getModel()); //nissan

We get the same result and this is known as Prototypal Inheritance. Also, each new instance don’t have its own getModel(), which we can see in below console log.



Discussion

No Comment Found