如果我在 2 个对象之间有 2 向关系,例如A与B相关,B与A相关,我怎样才能保持这种一致性,以使 2 个对象始终相互引用?
我正在努力将我非常简单的问题用语言表达出来,所以这里有一个非常简单的例子。我从Husband
和开始Wife
:
function Husband() { this.wife; }
function Wife() { this.husband; }
var harry = new Husband();
var wendy = new Wife();
harry.wife = wendy;
wendy.husband = harry;
从逻辑上讲,如果哈利的妻子是温蒂,那么温蒂的丈夫就是哈利。
我需要一种保持这种关系一致的方法。因此,我创建了一个 setter 方法,Husband
并通过以下划线前缀表示该wife
变量应被视为私有变量。
function Husband() {
this._wife;
this.setWife = function(wife) {
this._wife = wife;
wife.husband = this;
}
}
现在描述这种关系很简单,并鼓励一致性:
harry.setWife(wendy);
同样,最好有相反的选项:
wendy.setHusband(harry);
为此,我setHusband
在 上创建一个方法Wife
,并Husband
根据需要进行调整。
function Husband() {
this._wife;
this.setWife = function(wife) {
this._wife = wife;
// wife.husband = this; // <-- husband is now _husband (private)...
wife.setHusband(this); // <-- switching to a public method
}
}
function Wife() {
this._husband;
this.setHusband = function(husband) {
this._husband = husband;
husband._wife = this; // <-- Oops! _wife is private!
husband.setWife(this); // <-- Oops! this results in an infinite loop!
}
}
在这一点上,我遇到了障碍。我的新setHusband
方法需要能够保持一致性,但wife
现在是_wife
(私有的),并且调用setWife
会导致无限循环,因为它们相互交互。
我可以创建另一组类似的方法,reallyJustSetHusband
但这似乎很愚蠢。
我的难题并不是 JavaScript 特有的,但我在问题中提到了它,以防需要特定的方法。
在这两个对象之间实现一致性的最佳方法是什么?有什么我忽略的吗?
DOM 中的相似模式
在 DOM 中,如果调用parent.appendChild(child)
,则child.parentNode === parent
. 它们从不矛盾。如果父母有一个孩子,那么孩子有同一个父母。其他关系如nextSibling
也保持一致。