JavaScript 对象依赖于另一个对象

JavaScript objects dependency from another objects

有人可以解释或告诉我如何合并两个 JavaScript 对象,也许我可以称它们为小部件,然后一起工作。

假设我有一个大对象 (window) 代表一个资源管理器 window 和一个较小的对象 (toolbar) 表示带有各种按钮的工具栏。单独操作它们(添加、删除、更改属性等)我没有问题。但是我如何让它们一起工作呢? 例如,如果我想以这种方式从 window 中删除 toolbar window.Toolbar.Remove()

Remove() 函数是 toolbar 对象的一部分,会从 DOM 中自行删除 toolbar,但如何删除它的引用从 window 对象并将其设置为 null。我应该如何销毁这个 toolbar

如果我销毁主父对象 window,我应该如何销毁所有较小的对象,如 toolbar

非常感谢任何指点。

我在这里看到两个可能的选项:

1) 让子部件知道父部件。

你可以有这样的东西(伪代码):

window.addChild(name, WigdetClass) {
   this[name] = new WigdetClass(this);
}

// add toolbar
window.addChild('toolbar', Toolbar);

// Toolbar constructor accepts `parent` as parameter
Toolbar(parent) {
   this.parent = parent; 
}

Toolbar.prototype.Remove() {
   // remove self from the page
   ...
   // set parent reference to null
   parent.toolbar = null;
}

2) 或者你可以将"Remove"移动到父对象:

Window.prototype.RemoveChild(child) {
   // remove child from the document
   ...
   var propertyName = this.findChildName(child); // 'toolbar'
   this[propertyName] = null;
}