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

标签 javascript arrays inheritance circular-reference

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

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/

相关文章:

javascript - 无法对循环中的最后一项应用函数

javascript - 异步 JavaScript 解决方法

c# - LINQ 按数组内容分组

scala - 使用带有一些基类、抽象类或特征参数化列表的类型类的最佳方法

javascript - 如何使用 jquery 延迟删除 div?

java - 通过java代码生成javascript时<a>标签问题

arrays - WordPress 插件设置类中的动态数组选项

Javascript Array sort() 无法正确排序字符串数组

c# - 在我自己的 "UITableViewController"中使用默认实现使方法可选

java - 通用接口(interface)和实现 - 类型无法转换