Unable to understand <x> .prototype.constructor?
I have two classes Car and Maruti . When I use inheritance, assigning a Maruti prototype to the new Car object. Why do I need to install Maruti.prototype.constructor in Maruti . Shown in the code below.
function Car(){ } function Maruti(){ } Maruti.prototype = new Car() Maruti.prototype.constructor = Maruti Unable to understand the last line of code. Can someone explain in detail?
Considering this,
function Car(){ } and that the constructor property is a function prototype property
Now, if you look at the constructor of a new instance of Car
new Car().constructor === Car
You see that this is Car , then you install
function Maruti(){ } Maruti.prototype = new Car(); Remember that new Car().constructor === Car ?,
As such, it is now Maruti.prototype.constructor === Car , so it is shaded to an instance of Maruti , overriding the original Maruti.prototype.constructor
So, if you create a new instance of Maruti and search for the constructor
new Maruti().constructor === Car
You see this is Car , although new Maruti() is built on Maruti , not Car
Before setting Maruti.prototype = new Car prototype of Maruti has only one property, constructor , which is set as Maruti :
function Car() {} function Maruti(){} console.log(Maruti.prototype); // logs the following // { // constructor: Maruti // } Maruti.prototype = new Car; Maruti.prototype.constructor = Maruti; After you set the prototype from Maruti to the new Car , the constructor property is lost (because its not the same object). Instead, Maruti.prototype.constructor will now be Car (because it is inherited from Car.prototype ). Therefore, we again set the constructor property to Maruti .
For a better explanation, consider the following answer: fooobar.com/questions/85508 / ...