把一个孩子推向“;这个“;也会把它推到孩子身上'的孩子们..(Javascript)
Pushing a children to "this" will also push it in the child's childrens... (Javascript)
我有一些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 = [];
到"实体"构造函数。
相关文章:
- 为什么HTML5拖放的目标是孩子?(可排序列表)
- 在ReactJS中重新渲染孩子3次可以接受吗
- React.cloneElement:传递新的孩子或复制props.children
- jQuery:下拉;选项:第一个孩子“;作为选择器
- Jquery/Javascript—查找父级's的兄弟姐妹's儿童'的孩子
- 动态地向孩子添加类
- 设置一个孩子'Firebase上带有字符串的名称
- 当选择不同的父母时,我如何使条件形式的孩子消失并清除
- Javascript 样式的第 n 个孩子
- 错误“类型错误: $(..).孩子不是一种功能”
- 当孩子获得焦点时触发模糊事件
- 试图在 JavaScript 中提醒第二个孩子的 innerhtml
- 让孩子们没有子孩子
- 如何倾听孩子们的心声;s儿童停止传播的事件
- 按顺序遍历孩子们
- 如何添加类并让孩子们关注keydown函数
- 我如何得到“孩子们”?或者函数的内容
- 我可以通过props.children React JS将道具传递给孩子们吗
- 为孩子们创建一个JavaScript拖放编辑器,想要包含JSHint来检查语法-我该怎么做呢?
- 把一个孩子推向“;这个“;也会把它推到孩子身上'的孩子们..(Javascript)