gpt4 book ai didi

JavaScript-使用对象的方法从父数组中删除对象

转载 作者:行者123 更新时间:2023-11-30 12:22:04 25 4
gpt4 key购买 nike

我有一个父对象,它存储一个子数组并调用它们的一些方法。

var Parent = function ()
{
this.children = []
this.addChildren();
}

Parent.prototype.addChildren = function ()
{
for (var i=0; i < 5; i++)
{
this.children.push(new Child());
}

this.alterChildren();
}

Parent.prototype.alterChildren = function ()
{
this.children.forEach(function (child)
{
if (child.hasSomeProperty.foo)
{
child.alter();
}
});
}

然后是子对象。当某个事件发生在它们身上时,我需要它们被有效地销毁并且我 null 父级依赖的属性。

var Child = function ()
{
this.hasSomeProperty = {
foo: 'bar'
};
}

Child.prototype.onDestroyEvent = function ()
{
this.hasSomeProperty = null;
}

然后我想从父项的子项数组中删除这个子项并收集子项的垃圾。有没有一种优雅的方法可以在不循环引用或破坏现有结构的情况下做到这一点?

最佳答案

如果您希望子级向父级发送消息,那么子级需要有对父级的引用。

Parent.prototype.addChildren = function ()
{
for (var i=0; i < 5; i++)
{
this.children.push(new Child(this));
}
this.alterChildren();
}
Parent.prototype.removeChild = function (child)
{
var i = this.children.indexOf(child);
return this.children.splice(i, 1);
}

var Child = function (parent)
{
this.parent = parent;
this.hasSomeProperty = {
foo: 'bar'
};
}

Child.prototype.destroy = function ()
{
this.hasSomeProperty = null;
this.parent.removeChild(this);
}

关于JavaScript-使用对象的方法从父数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30659053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com