2017-09-08 32 views
0

爲什麼我們需要在繼承之後將Child.prototype.constructor屬性設置爲Child。例如爲什麼重寫繼承的構造函數字段

function Parent(a){ 
    this.a = a; 
} 

function Child(a, b){ 
    Parent.call(this. a); 
    this.b = b; 
} 
Child.prototype = Object.create(Parent.prototype); 
Child.prototype.constructor = Child // 1)** 

當我看到構造函數的實例將是相同的,而不// 1) **

爲什麼我們需要這個// 1) **行?

+2

可能重複[爲什麼需要設置原型構造?](https://stackoverflow.com/questions/8453887/why-is-it-necessary -to-設置的原型構造函數) –

回答

0

因爲它不應該是相同

通過語言的語法Child.prototype.constructor應該是Object.create(Parent.prototype).constructor的實例,它實際上是Parent.prototype.constructor

然後,它至多執行或對引擎的優化。但它不能信任,所以// 1)行是爲了確保它