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

JavaScript- Remove object from parent array with an object's method

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

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);
}