1

标题实在是太乱了,找不到更好的了。

假设我有:

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

我想保存pb对对象的引用pa。可能吗?

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

然而,我们可以混合这两种方法,这样你就只有一个原型,但有不同的构造函数:

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 (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 回答
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 回答