我想实例化两个相互依赖的类,如下所示:
this.a = null;
this.b = null;
this.a = new A({
b: this.b
}
this.b = new B({
a: this.a
}
问题是,如果我这样做,如果我将它交给构造函数,b
将为 null。如何才能“优雅”地解决这个先有鸡还是先有蛋的问题呢?或者我是否必须在通过方法实例化后设置对 b
的引用?
最佳答案
我建议将问题移交给 A
的构造函数和B
.
在这种情况下,您可以利用条件(间接)递归:
function A(b)
{
this.b = b || new B(this);
}
function B(a)
{
this.a = a || new A(this);
}
通过使用 ||
,您确保调用A(this)
和B(this)
自己不会创造另一个B
/A
从而结束了“先有鸡还是先有蛋”的问题。
然后你可以像这样使用它们
this.a = new A();
this.b = this.a.b;
或
this.b = new B();
this.a = this.b.a;
如果存在A
的情况或B
合法拥有他们的.b
或.a
设置为null
,您可以使用undefined
和null
区分这些情况,并相应地更改构造函数:
function A(b)
{
this.b = b === undefined ? new B(this) : b;
}
function B(a)
{
this.a = a === undefined ? new A(this) : a;
}
如果A
和B
需要为其构造函数提供其他参数,或者由于某些其他原因不应构造另一个 B
或A
他们自己,您可以将 this
传递给他们来自创建范围的实例(因为它包含 a
和 b
字段,其值仅在访问时确定,而不是在构造 A
和 B
时确定):
function A(container)
{
this.container = container;
// Access B via this.container.b
}
function B(container)
{
this.container = container;
// Access A via this.container.a
}
this.a = new A(this);
this.b = new B(this);
如果A
和B
并不意味着具有对容器对象的完全访问权限,您可以创建要在其位置使用的中间对象,例如:
var aProxy = { a: null };
var bProxy = { b: null };
this.a = aProxy.a = new A(bProxy);
this.b = bProxy.b = new B(aProxy);
如果由于某种原因这也是 Not Acceptable ,那么您唯一的选择就是稍后更改 a.b
的值和b.a
通过手动分配或通过 setter 函数。
关于javascript - 循环引用实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39065519/