2012-04-06 17 views
0

内のオブジェクトのグループ全体の属性特定の属性をオブジェクト間で共有するために、コンストラクタ関数のプロトタイプに設定することができます。共有はJavaScriptでJavascriptを

function B() {} 
B.prototype.b = 'B0'; 

しかし、中間の状況ではどうすればよいですか?基本的には、すべての構築されたオブジェクトがプロトタイプからプロパティを継承する既存のコードがありますが、グループのすべてのメンバーが属性を共有するように複数のグループに分割する必要があります。

何とかコンストラクタ関数Bを特殊化する方法はありますか?

答えて

1

B.prototype.bあなたが推測するように静的なプロパティを作成しません。彼らは、その値を上書きするまで、それはもう少し複雑よりもだ、プロトタイプを共有し、他のインスタンスとその価値に添付性質があることを意味:

var Foo = function(){ 
}; 
Foo.prototype.bar = 'bar'; 

var f1 = new Foo(); 
console.log(f1.bar); //outputs 'bar' 
var f2 = new Foo(); 
console.log(f2.bar); //outputs 'bar' 

f2.bar = 'notbar'; 
console.log(f2.bar); //outputs 'notbar' 
console.log(f1.bar); //outputs 'bar' 

唯一の方法は、「本当の」静的な性質を持つためにそれらを結合することですコンストラクタ関数自体へ:Foo

Foo.bar2 = 'bar2'; 

インスタンスがFoo.bar2とその値にアクセスする必要があります。

var Base = function(){ 
}; 
Base.prototype.getSomething = function(){ 
    return this.constructor.something; 
}; 
Base.prototype.setSomething = function(value){ 
    this.constructor.something = value; 
} 
var Group1 = function(){ 
}; 
Group1.prototype = new Base(); //classical inheritance 
Group1.prototype.constructor = Group1; 
Group1.something = 'something'; 
var Group2 = function(){ 
}; 
Group2.prototype = new Base(); //classical inheritance 
Group2.prototype.constructor = Group2; 
Group2.something = 'something else'; 

var g1a = new Group1(); 
var g1b = new Group1(); 
var g2a = new Group2(); 
var g2b = new Group2(); 

g1a.setSomething('whatever'); 

console.log(g1a.getSomething()); //outputs 'whatever' 
console.log(g1b.getSomething()); //outputs 'whatever' 
console.log(g2a.getSomething()); //outputs 'something else' 
console.log(g2b.getSomething()); //outputs 'something else' 

警告:

は、だからあなたの質問への答えは、このように、グループごとに、「サブクラス」(基本コンストラクタ関数から自分のプロトタイプを継承コンストラクタ関数)を作成し、サブクラスごとにプロパティを添付することです:

http://creynders.wordpress.com/2012/04/01/demiurge-3-types-of-javascript-inheritance-2/

+0

グレート:Group1.prototype = new Base();は実際に悪い習慣ですが、私はその理由を説明しているだけで数日前に相続の3種類についてブログ記事を書きました!しかし、もし私のコンストラクタが実際に議論をしたら? –

+0

正確にはどういう意味ですか? Group1とGroup2は、引数を持つことができる通常のコンストラクタです。スーパーコンストラクタを呼び出す必要がある場合は、 'Base.call(this) 'のように直接呼び出すか、私のblogpostのように' __super__'トリックを行うことができます。 – Creynders

関連する問題