Hello everyone, I’ve been seeing this line of code a lot lately or something similar to it’s nature.
Car.prototype = new Vehicle(true, true);
Car.prototype.constructor = Car;
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”.
Here’s the rest if you want to know.
function Vehicle(hasEngine, hasWheels) {
this.hasEngine = hasEngine || false;
this.hasWheels = hasWheels || false;
}
Vehicle.prototype.power = function () {
console.log("RESCUE");
}
function Car (make, model, hp) {
this.hp = hp;
this.make = make;
this.model = model;
}
Car.prototype = new Vehicle(true, true);
//Car.prototype.constructor = Car;
Car.prototype.displaySpecs = function () {
console.log(this.make + ", " + this.model + ", " + this.hp + ", " + this.hasEngine + ", " + this.hasWheels);
}
var audi = new Car ("Audi", "A4", 150);
audi.displaySpecs();
// logs: Audi, A4, 150, true, true
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.
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.
[FONT=Courier New]function Car() {
}
console.log(Car.prototype.constructor == Car); // true – so far so good
Car.prototype = new Vehicle();
console.log(Car.prototype.constructor == Car); // false – what happened?[/FONT]
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.