What does the last line mean? I can delete this line out and it doesn't seem to change the code in any way. Do you have any practical examples why I should always set an object.prototype.constructor = object? What do I miss? What can't I access if I don't type this line?

Even if I comment out this line, I get what I want which is that Car inherits the properties of Vehicle, and audi variable gets access to both "classes".

When we replaced Car's prototype with an instance of vehicle, we lost Car's constructor property, and in its place, we inherit Vehicle's constructor property. This is almost always not what we want, so after we set up inheritance, we then fix the constructor property.

Car.prototype.constructor = Car;

ali0020
—
2012-03-05T01:18:11Z —
#4

chris_upjohn said:

Hi ali0020 and welcome to SitePoint,

To get straight into it you don't need the constructor prototype as all your doing is referencing the new instance of the class which you can use like any other prototype from that point on.

Hello Chris! And hm... I see...

Jeff_Mott said:

Ali, when you create a "class", the prototype object comes with an automatic constructor property.

function Vehicle() {}

console.log(Vehicle.prototype.constructor == Vehicle); // true

The constructor property allows instances to access the function that created them. One use of this is to test an object's type.

if (someObj.constructor == Vehicle) {}

But things get a little hairy when we get into inheritance.

function Car() {}

console.log(Car.prototype.constructor == Car); // true -- so far so good

When we replaced Car's prototype with an instance of vehicle, we lost Car's constructor property, and in its place, we inherit Vehicle's constructor property. This is almost always not what we want, so after we set up inheritance, we then fix the constructor property.

Car.prototype.constructor = Car;

May I ask... what's wrong with just leaving it the Car's constructor property as it is? Is there any real world example where

Car.prototype = new Vehicle();

will hurt my code? What's the loss if I forget to type

Car.prototype.constructor = Car;

?

Yes I can see the property has been reset and we can see this by check it with the console... but... is it bad? What code so

Thanks.

Jeff_Mott
—
2012-03-05T01:38:35Z —
#5

ali0020 said:

What's the loss if I forget to type

Car.prototype.constructor = Car;

If you never use the constructor property, nor ever intend to use it, then there's no loss.