2015-06-25 80 views
2

難道一些javascript ninja會向我解釋爲什麼我的構造函數在這裏被搞糟了?我覺得我正在實施原型鏈。我知道我可以使用Object.create,但我只是想了解爲什麼這不起作用。瞭解Javascript原型鏈和繼承 - 示例

var Vehicle = function() {} 
Vehicle.prototype.accelerate = function() { console.log('VRRRROOOOOOOM') } 
Vehicle.prototype.brake = function() { console.log('SCREEEEECH') } 

var Car = function() {} 
Car.prototype = new Vehicle 
Car.prototype.openTrunk = function() { console.log('POP') } 
Car.prototype.closeTrunk = function() { console.log('CLUNK') } 

// Test 
var mazda = new Car 
console.log(mazda) // prototype chain is right 
console.log(mazda.constructor === Car) // should be true 
console.log(mazda.constructor === Vehicle) // should be false 

https://jsfiddle.net/6j43r8qg/1/

回答

4

constructor屬性是基於原型定義。

Car.prototype = new Vehicle 

覆蓋原型,併爲其分配Vehicle的實例。所有Vehicle實例繼承constructor,其指向Vehicle,從Vehicle.prototype

enter image description here

+0

謝謝,這是有道理的。但是誰的錯是這個,我的還是javascript的? –

+0

是的。這就是爲什麼您在覆蓋原型之後通常會設置「Child.prototype.constructor = Child」的原因。請參閱[爲什麼需要設置原型構造函數?](http://stackoverflow.com/q/8453887/218196) –

+0

@SpencerAvinger:不確定是否可以在這裏提到「錯誤」。您重寫了包含'constructor'屬性的'Child.prototype'。所以我猜它是你的錯? –

0

而且我覺得instanceof會的方式來檢查,如果事情是什麼

console.log(mazda) // prototype chain is right 
console.log(mazda instanceof Car) // should be true 
console.log(mazda instanceof Vehicle) // should be *true?!*