标题真的令人困惑,我无法找到更好的标题。
假设我有:
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
对象的引用。有可能吗?
答案 0 :(得分:1)
函数used as a constructor只有对新实例的引用,继承自其原型。
要使其保持对原始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 = {
…
};
答案 1 :(得分: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);
答案 2 :(得分: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"