Child1.prototype = BaseClass.prototype;
Should be Child1.prototype = Object.create(BaseClass.prototype)
You don't want the prototype object to be the same, you want a new prototype object that inherits from BaseClass
実例
Disclaimer: Object.create
is ES5, use the ES5-shim for legacy platform support.
あなたにもっと徹底的な例を与えるために:
// 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;
プロトタイプオブジェクトと共に ConstructorFunction.prototype
オブジェクトの新しいインスタンスを与える new
で呼び出すことができる関数である "Constructor関数"をリンクする必要があります。これは基本的にあなたが手作業で行う必要がある接着剤です。なぜなら、ESはこれをあなたのためにしていないからです。
これを忘れた場合、コンストラクタ関数( X.constructor
)にインスタンスを継承させる .prototype
プロパティはありません。
var Child = Object.create(Base);
[[Prototype]]
が Base
の新しいオブジェクトを作成します。これは基本的にプロトタイプチェーンの始まりです
Child -> ([[Prototype]] = Base) -> ([[Prototype]] = Object.prototype) -> null
Child.x = ...
ここでは、Childオブジェクトが継承するメソッドのインスタンスであるプロパティを子オブジェクトに追加します。基本的には、継承する新しいプロトタイプオブジェクトを作成しています。すべてのインスタンスがメソッドを共有し、プロトタイプチェーンまでのメソッドを共有します( Base
を含む)。
ChildFactory = Child.constructor;
new
キーワードは、プロトタイプオブジェクトではなくコンストラクタ関数でのみ機能するので、基本的には「プロトタイプオブジェクト変数をコンストラクタ関数変数に切り替える」必要があります
個人的には、「クラス」を構築するときには、プロトタイプオブジェクトが直接扱うのが楽しく、インスタンスを作成するときには、コンストラクターが扱うのが楽しいことがわかります。
Now when we call var c = new Child(41);
things
をインクリメントして定義したコンストラクタ関数を呼び出し、基本コンストラクタを呼び出します。
この時点で、cのプロトタイプチェーンは次のようになります
c -> ([[Prototype]] = Child)
-> ([[Prototype]] = Base)
-> ([[Prototype]] = Object.prototype)
-> null