2013-02-17 115 views
0

我有一些实体/组件代码在JavaScript中。这主要是完成,但我碰到了这个奇怪的问题。我的实体有一个childrens数组,在其中我推动儿童,其他一些数组(componentsDictionary,将重命名不用担心,它曾经是一个字典),因为它的组件。推动一个孩子“这个”也将推到它的孩子的孩子......(Javascript)

现在,当我调用this.childrens.push(obj)时,它会在this.childrens和obj.childrens中推送对象...当我更新渲染树时,会导致无限循环。

大概在JS闭包的很奇怪处理一个问题...

这里是有问题的代码:

Entity.prototype = { 
    childrens : [], 
    componentsDictionary : [], 
    sharedAttributes : {}, // This data is shared for all components 
    debugName : "Entity Default Name", 
    bubblee : null, 

    Add : function(obj) { 
     if (obj instanceof Entity) { 
      alert(obj.debugName); // alerts "entity 0" 
      alert(this.debugName); // alerts "root" 

      alert(obj.childrens.length); // "alerts 0" 
      this.childrens.push(obj); 
      alert(obj.childrens.length); // "alerts 1" 
      // how the f... !%!??!%11? 
     } 
     else if (obj instanceof IComponent) { 
      this.componentsDictionary[obj.type].push(obj); 
     } 
     else { 
      throw new Exceptions.IllegalAction("Attempted to add something else than an entity or a component to an entity."); 
     } 
    }, 

非常感谢!

尼克

回答

1

因为你已经把“儿童”数组原型对象,它是由“实体”的每个实例共享。换句话说,只有一个数组。

如果你想为每个实例单独的阵列,从原型中删除,并添加

this.childrens = []; 

的“实体”的构造。

+0

当然也是“componentsDictionary”。 – Pointy 2013-02-17 16:55:01

+0

我以为Scope.prototype.var将是一个属性和Scope.var将是一个静态属性...似乎我需要检查我的ecmascript基本面。 – NGauthier 2013-02-17 16:57:16

+0

@NGauthier原型属性全部共享 - 作为函数的属性的处理方式与没有处理的属性不同。 – Pointy 2013-02-17 17:00:11

相关问题