Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why set prototype's constructor to its constructor function? [duplicate]

Tags:

javascript

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?

like image 425
Matt Avatar asked Feb 18 '12 17:02

Matt


1 Answers

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) { ... }
like image 58
user1106925 Avatar answered Oct 20 '22 19:10

user1106925