有人可以解释或告诉我如何合并两个JavaScript对象,也许我可以称之为小部件,然后一起工作。
假设我有一个大对象(窗口)代表一个资源管理器窗口和一个较小的对象(工具栏),它代表带有各种按钮的工具栏。单独操作它们(添加,删除,更改属性等)我没有问题。但是我如何让它们一起工作呢?
例如,如果我想以这种方式从窗口中删除工具栏
window.Toolbar.Remove()
Remove()
函数是toolbar
对象的一部分,会从DOM中删除工具栏,但如何从窗口对象中删除它的引用并设置它到null
。我应该摧毁这个toolbar
一些怎么样?
如果我销毁主要父对象window
,我应该如何销毁所有较小的对象,如toolbar
?
任何指针都非常赞赏。
答案 0 :(得分:1)
我在这里看到两种可能的选择:
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)或者您可以将“删除”移动到父对象:
Window.prototype.RemoveChild(child) {
// remove child from the document
...
var propertyName = this.findChildName(child); // 'toolbar'
this[propertyName] = null;
}