ここで帯域幅を節約するには、「JavaScript で「クラス」をエミュレートするにはどうすればよいですか? (サードパーティ ライブラリの有無にかかわらず)」に関する私の回答へのリンクです。これには、追加の参照と例が含まれています。
簡単に言えば、JavaScript のプロトタイプOOの核心は委譲です。このスタイルの OOP では、同じ「クラス」のさまざまなオブジェクトが、メソッドとプロパティの処理を同じプロトタイプ (通常は 3 番目のオブジェクト) に委譲できます。
var foo = {
property: 42,
inc: function(){
++this.counter;
},
dec: function(){
--this.counter;
}
};
// Note: foo does not define `counter`.
プロトタイプとして foo を持つオブジェクトのコンストラクターを作成しましょう。事実上、処理されないものはすべて foo に委譲されます。
var Bar = function(){
this.counter = 0;
};
Bar.prototype = foo; // This is how we set up the delegation.
// Some people refer to Bar (a constructor function) as "class".
var bar = new Bar();
console.log(bar.counter); // 0 --- Comes from bar itself
console.log(bar.property); // 42 --- Not defined in bar, comes from foo
bar.inc(); // Not defined in bar => delegated to foo
bar.inc();
bar.dec(); // Not defined in bar => delegated to foo
// Note: foo.inc() and foo.dec() are called but this === bar
// that is why bar is modified, not foo.
console.log(bar.counter); // 1 --- Comes from bar itself
inc()
バー上で直接定義しましょう:
bar.inc = function(){
this.counter = 42;
};
bar.inc(); // Defined in bar => calling it directly.
// foo.inc() is not even called.
console.log(bar.counter); // 42 --- Comes from bar
単一継承チェーンの設定:
var Baz = function(){
this.counter = 99;
};
Baz.protype = new Bar();
var baz = new Baz();
console.log(baz.counter); // 99
baz.inc();
console.log(baz.counter); // 100
console.log(baz instanceof Baz); // true
console.log(baz instanceof Bar); // true
console.log(baz instanceof Object); // true
いいですね。