把一个孩子推向“;这个“;也会把它推到孩子身上'的孩子们..(Javascript)

Pushing a children to "this" will also push it in the child's childrens... (Javascript)

本文关键字:孩子 孩子们 Javascript 这个 一个      更新时间:2023-09-26

我有一些javascript中的实体/组件代码。大部分都完成了,但我遇到了一个非常奇怪的问题。我的实体有一个子数组,我在其中推送子数组,还有一些其他数组(componentsDictionary,将被重命名,别担心,它曾经是一个dict)用于它的组件。

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

可能是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.");
        }
    },

非常感谢!

Nic

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

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

this.childrens = [];

到"实体"构造函数。