2012-02-18 241 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) { ... } 
相關問題