这个标题真的很困惑,我找不到更好的标题。
假设我有:
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
对象的引用。可能吗?
最佳答案
一个函数used as a constructor仅对新实例的引用,继承自其原型(prototype)。
要使其维护对原始 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
但是,这样做的缺点是为每个 A
实例创建一个新的 B
构造函数(具有自己的原型(prototype)对象)。更好的是像
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
但是,我们可以混合使用这两种方法,这样您就只有一个原型(prototype)但有不同的构造函数:
function A() {
var that = this;
this.pa = { x: 1 };
this.B = function() {
this.pb = that.pa;
};
this.B.prototype = A.Bproto;
}
A.Bproto = {
…
};
关于javascript - 获取对包含构造函数属性的对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326699/