0

我在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.");
        }
    },

非常感谢!

网卡

4

1 回答 1

1

因为您已将“childrens”数组放在原型对象上,所以它由“Entity”的每个实例共享。换句话说,只有一个数组。

如果您希望每个实例有一个单独的数组,请将其从原型中删除并添加

this.childrens = [];

到“实体”构造函数。

于 2013-02-17T16:53:47.170 回答