把孩子推到;这";也会将其推入儿童';孩子们。。。(Javascript)
我有一些javascript中的实体/组件代码。基本上已经完成了,但我遇到了一个非常奇怪的问题。我的实体有一个childrens数组,我在其中推送childrens,还有一些其他数组(componentsDictionary,将被重命名,别担心,它以前是dict)用于它的组件 现在,当我调用这个.childrens.push(obj)时,它同时在这个.childrens和obj.childrens内部推动对象。。。在更新渲染树时导致无限循环 可能是JS中的闭包处理非常奇怪的问题 下面是有问题的代码:把孩子推到;这";也会将其推入儿童';孩子们。。。(Javascript),javascript,oop,closures,ecmascript-5,Javascript,Oop,Closures,Ecmascript 5,我有一些javascript中的实体/组件代码。基本上已经完成了,但我遇到了一个非常奇怪的问题。我的实体有一个childrens数组,我在其中推送childrens,还有一些其他数组(componentsDictionary,将被重命名,别担心,它以前是dict)用于它的组件 现在,当我调用这个.childrens.push(obj)时,它同时在这个.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.");
}
},
非常感谢
Nic因为您已将“childrens”数组放在原型对象上,所以它由“Entity”的每个实例共享。换句话说,只有一个数组
如果希望每个实例都有一个单独的数组,请将其从原型中删除并添加
this.childrens = [];
“实体”构造函数。我认为Scope.prototype.var是一个属性,Scope.var是一个静态属性。。。似乎我需要检查我的ecmascript基础知识。@n授权原型属性都是共享的-函数属性与非函数属性没有区别对待。你完全正确,需要重构一些其他内容,谢谢,我会尽快选择你的awnser