1

The title is really confusing, I couldn't find a better one.

Suppose I have:

var A = function (){
    this.pa = { x: 1 };
};

A.prototype.B = function (){
    this.pb = /* a reference to { x: 1 } */;
};

var a = new A ();
var b = new a.B ();
console.log (b.pb.x); //should print 1
a.pa.x = 2;
console.log (b.pb.x); //should print 2

I want to save in pb a reference to the pa object. Is it possible?

4

3 に答える 3

1

コンストラクターとして使用される関数には、プロトタイプから継承した新しいインスタンスへの参照のみがあります。

元のインスタンスへの参照を維持するには、コンストラクターをクロージャー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 = {
    …
};
于 2013-03-10T21:14:02.490 に答える
0
var A = function (){
    this.pa = { x: 1 };
};

A.prototype.B = function (a){

     this.pb = a.pa;
};
var a = new A ();

var b = new  a.B(a);
console.log(b.pb.x); //should print 1
a.pa.x = 2;
console.log(b.pb.x);
于 2013-03-10T20:06:16.357 に答える
0

まあ、それは私が望むものではありませんが、非常に近いです:

var A = function (pa){
    this.pa = pa;
};

A.prototype.B = function (a){
    if (this instanceof A.prototype.B){
        if (!a) throw "error";
        this.pb = a.pa;
        return;
    }
    return new A.prototype.B (this);
};

var a = new A ({ x: 1 });
var b = a.B ();
console.log (b.pb.x); //1
a.pa.x = 2;
console.log (b.pb.x); //2

new a.B () //throws "error"
于 2013-03-10T20:52:20.110 に答える