コンストラクターとして使用される関数には、プロトタイプから継承した新しいインスタンスへの参照のみがあります。
元のインスタンスへの参照を維持するには、コンストラクターをクロージャーA
に入れる必要があります。B
function A() {
var that = this;
this.pa = { x: 1 };
this.B = function() {
this.pb = that.pa;
};
};
var a = new A ();
var b = new a.B ();
console.log (b.pb.x); // does print 1
a.pa.x = 2;
console.log (b.pb.x); // does print 2
ただし、これには、インスタンスB
ごとに(独自のプロトタイプオブジェクトを使用して)新しいコンストラクターを作成するという欠点がありA
ます。のようなものが良いでしょう
function A() {
this.pa = { x: 1 };
}
A.B = function() {
this.pb = null;
};
A.prototype.makeB = function() {
var b = new A.B();
b.pb = this.pa;
return b;
};
// you can modify the common A.B.prototype as well
var a = new A ();
var b = a.makeB();
console.log (b.pb.x); // does print 1
a.pa.x = 2;
console.log (b.pb.x); // does print 2
それでも、2つのアプローチを組み合わせて、プロトタイプは1つだけで、コンストラクターは異なるようにすることができます。
function A() {
var that = this;
this.pa = { x: 1 };
this.B = function() {
this.pb = that.pa;
};
this.B.prototype = A.Bproto;
}
A.Bproto = {
…
};