prototype
是構造函數的一個特殊的屬性,而不是實例的。
當你調用與new Func()
的構造函數,該引擎將創建新的對象,從Func.prototype
繼承,然後設置this
的構造函數中引用新的對象。
所以,除了this.prototype
只是一個普通的屬性,繼承已經發生在分配發生時。
由於您沒有將任何方法分配給MyClass.prototype
,因此您無需在此處進行任何原型繼承。所有你需要做的就是應用MyClass
使用.call
[MDN]新創建的實例:
var SecondClass = function(b) {
MyClass.call(this, b);
this.getB = function() {
return 6;
}
};
然而,你應該add all methods that are shared by instances to the prototype然後讓SecondClass
繼承的每個實例從它。這是一個完整的設置就怎麼看起來像:
var MyClass = function(b) {
this.a = b;
}
MyClass.prototype.getA = function() {
return this.a;
};
var SecondClass = function(b) {
// call parent constructor (like 'super()' in other languages)
MyClass.call(this, b);
}
// Setup inheritance - add 'MyClass.prototype' to the prototype chain
SecondClass.prototype = Object.create(MyClass.prototype);
SecondClass.prototype.getB = function() {
return 6;
};
var a = new SecondClass(2);
console.log(a.getA());
這一切will become easier in ES6的。
「原型」不是關鍵字。 – Pointy 2013-04-23 15:56:43
'return that.a;'應該是'return this.a;'btw。 – 2013-04-23 16:05:37