我定義使用這個(prototype
)方法有兩個JavaScript類:Javascript繼承與簡潔的原型賦值語法
function Parent() {
this.a = 1;
}
Parent.prototype = {
hello : function() {
return "Hello I'm Parent!";
},
setA : function (a) {
this.a = a;
}
};
和
function Child() {
this.b = 2;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
Child.prototype = {
hello : function() {
return "Hello I'm Child!";
},
setB : function (b) {
this.b = b;
}
};
我使用這種技術,因爲我覺得標準語法太冗長和稀疏:
Child.prototype.hello = function() {...};
Child.prototype.setB = function (b) {...};
這裏的問題是,我覆蓋Child.prototype
(從Parent
繼承)失去.setA()
方法(但正確覆蓋.hello()
)。
是合併兩個原型的解決方案?怎麼樣?
這種方法會導致問題嗎?
考慮這個繼承:'Child.prototype =的Object.create(新父());' –
@馬蒂亞斯可以使用的Object.create或一個輔助函數,用於在設置繼承的原型部分時防止創建一個Parent實例,所以它應該是:'Child.prototype = Object.create(Parent.prototype);'您和OP執行它的每個實例特定成員的方式在Child實例中創建一個Child實例(Parent.apply(this,arguments))時,父'this.someting'被放置在Child原型上,並且(如果您正確地做到這一點)立即被遮蔽。或更糟;程序員假定Child有Parent的實例成員,並沒有意識到他們實際上是共享的。 – HMR