Child1.prototype = BaseClass.prototype;
應該Child1.prototype = Object.create(BaseClass.prototype)
你不想原型對象是相同的,你想要一個新的原型對象,從BaseClass
繼承
Live Example
免責聲明:Object.create
是ES5,使用ES5-shim遺留平臺的支持。
爲了讓您更全面的例子:
// Create base prototype
var Base = {
method: function() {
return this.things;
},
constructor: function (things) {
this.things = things;
}
};
// Link constructor and prototype
Base.constructor.prototype = Base;
// Create child prototype that inherits from Base
var Child = Object.create(Base);
// overwrite constructor
Child.constructor = function (things) {
things++;
Base.constructor.call(things);
}
// Link constructor and prototype
Child.constructor.prototype = Child;
// Swap prototype and constructor around to support new
ChildFactory = Child.constructor;
var c = new ChildFactory(41);
console.log(c.method()); // 42
視覺:
var Base = { ... }
在這裏,我們簡單地創建方法和屬性的對象。我們希望能夠創建此對象的實例。所以Base
是一個「類」和所有它的方法和屬性可以從實例(包括constructor
)進行訪問。
Base.constructor.prototype = Base;
您需要關聯的「構造函數」,這是你可以用new
調用一個函數,它會給你的對象ConstructorFunction.prototype
的新實例一起與原型對象。這基本上是一些你需要手動完成的粘合劑,因爲ES不會爲你做這件事。
如果您忘了這麼做,那麼構造函數(即X.constructor
)沒有.prototype
屬性來使實例繼承。
var Child = Object.create(Base);
創建一個新的對象,其[[Prototype]]
爲Base
。這基本上是你的原型鏈
Child -> ([[Prototype]] = Base) -> ([[Prototype]] = Object.prototype) -> null
Child.x = ...
現在我們添加這是兒童的方法實例將繼承屬性,我們的子對象的開始。基本上我們正在創建一個新的原型對象來繼承。所有實例都將共享這些方法,並在原型鏈上共享方法(包括Base
)。
ChildFactory = Child.constructor;
的new
關鍵字只能在構造函數,而不是原型對象,因此,我們需要從根本上說,建立「類時,「我們的原型對象變量切換到構造函數變量」
個人「我發現原型對象非常令人愉快,可以直接處理,並且在創建實例時我發現構造函數很適合處理。
現在,當我們調用var c = new Child(41);
它將調用我們定義的構造函數,這將增加things
,然後調用基構造函數。
注意此時C的原型鏈看起來像
c -> ([[Prototype]] = Child)
-> ([[Prototype]] = Base)
-> ([[Prototype]] = Object.prototype)
-> null
這裏是在JS使用繼承的許多方面是一個很好的資源:HTTP:/ /www.3site.eu/doc/ –