Regarding a line of this script:
function Vehicle(hasEngine, hasWheels) {
this.hasEngine = hasEngine || false;
this.hasWheels = hasWheels || false;
}
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 myAudi = new Car ("Audi", "A4", 150);
myAudi.displaySpecs(); // logs: Audi, A4, 150, true, true
My question is: what does
Car.prototype.constructor = Car;
do? More importantly, what are the consequences of not doing this, and in which circumstances is it MOST useful?
It restores the .constructor
property that was on the original prototype object that you overwrote. People restore it because it's expected to be there.
Some people like to do...
if (my_obj.constructor === Car) { ... }
This isn't required, since instanceof
is a better test IMO.
if (my_obj instanceof Car) { ... }
if (my_obj instanceof Vehicle) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With