【问题标题】:Pushing a children to "this" will also push it in the child's childrens... (Javascript)将孩子推送到“this”也会将其推送到孩子的孩子...(Javascript)
【发布时间】:2013-02-17 16:48:17
【问题描述】:

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

非常感谢!

网卡

【问题讨论】:

    标签: javascript oop closures ecmascript-5


    【解决方案1】:

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

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

    this.childrens = [];
    

    到“实体”构造函数。

    【讨论】:

    • 我认为 Scope.prototype.var 将是一个属性,而 Scope.var 将是一个静态属性......似乎我需要检查我的 ecmascript 基础知识。
    • @NGauthier 原型属性都是共享的——作为函数的属性与非函数的属性没有区别。
    • 你说得对,要重构一些其他的东西,谢谢,会尽快选择你的遮阳篷
    猜你喜欢
    • 2015-01-07
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多