获取持有作为构造函数的属性的对象的引用

标题真的很混乱,我找不到更好的。

假设我有:

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 aB (); console.log (b.pb.x); //should print 1 a.pa.x = 2; console.log (b.pb.x); //should print 2 

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

用作构造函数的函数只有一个对新实例的引用,从原型inheritance。

为了使其保持对原始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 aB (); console.log (b.pb.x); // does print 1 a.pa.x = 2; console.log (b.pb.x); // does print 2 

但是,这有一个缺点,即为每个A实例创build一个新的B构造函数(带有自己的原型对象)。 最好会是这样的

 function A() { this.pa = { x: 1 }; } AB = function() { this.pb = null; }; A.prototype.makeB = function() { var b = new AB(); b.pb = this.pa; return b; }; // you can modify the common ABprototype 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 = { … }; 
 var A = function (){ this.pa = { x: 1 }; }; A.prototype.B = function (a){ this.pb = a.pa; }; var a = new A (); var b = new aB(a); console.log(b.pb.x); //should print 1 a.pa.x = 2; console.log(b.pb.x); 

那么,这不是我想要的,但是非常接近:

 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 = aB (); console.log (b.pb.x); //1 a.pa.x = 2; console.log (b.pb.x); //2 new aB () //throws "error"