2012-02-18 143 views
21

关于此行的脚本:为什么要将原型的构造函数设置为其构造函数?

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 

我的问题是:什么

Car.prototype.constructor = Car; 

吗?更重要的是,不这样做的后果是什么,在哪些情况下它最有用?

回答

18

它恢复原来覆盖的原型对象上的.constructor属性。人们将其恢复,因为它预计会在那里。

有些人喜欢做......

if (my_obj.constructor === Car) { ... } 

这不是必须的,因为instanceof是一个更好的测试IMO。

if (my_obj instanceof Car) { ... } 

if (my_obj instanceof Vehicle) { ... } 
相关问题