我在javascript中有一些实体/组件代码。大部分都完成了,但我遇到了这个非常奇怪的问题。我的实体有一个子数组,我在其中推送子元素,还有一些其他数组(componentsDictionary,将被重命名,别担心,它曾经是一个字典)用于它的组件。
现在,当我调用 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.");
}
},
非常感谢!
网卡