JavaScript-使用对象从父数组中删除对象';s法

JavaScript-使用对象从父数组中删除对象';s法,javascript,arrays,inheritance,circular-reference,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()); } thi

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

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

然后我想从父数组的子数组中删除这个子数组,并将子数组垃圾收集起来。有没有一种优雅的方法可以做到这一点,而不需要循环引用或破坏我现有的结构?

如果您希望孩子向家长发送消息,那么孩子需要有对家长的引用

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

你为什么担心垃圾收集?我省略了这里的具体情况,但是子对象实际上包含一个Phaser精灵,它在游戏循环中调用了方法。我需要销毁Phaser sprite(因为在那里使用它非常昂贵),然后在父数组中销毁子元素以避免错误。垃圾收集器会解决这个问题。但如果子元素没有从数组中拼接出来,则不会,对吗?该子级仍然存在,并且需要继续,以便在父级调用child.sprite.doSomething()循环引用时不会抛出错误。循环引用仅对纯粹的引用计数GC有问题。JavaScripts GC的功能要强大得多。看,这不是在创建一个循环引用吗?
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);
}