我建议将问题移至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);
如果由于某种原因这也是不可接受的,那么您唯一的选择是稍后通过手动分配或通过 setter 函数更改 a.b 和 b.a 的值。