Javascript 链接对象?
我现在正在经历一些非常奇怪的物体行为。 我有一个模板对象:Javascript 链接对象?,javascript,object,Javascript,Object,我现在正在经历一些非常奇怪的物体行为。 我有一个模板对象: template: { trigger: { width: 32, height: 32, delay: 0 }, player: { direction: { value: "right", options: "left|rig
template: {
trigger: {
width: 32,
height: 32,
delay: 0
},
player: {
direction: {
value: "right",
options: "left|right"
}
},
apple: {
direction: {
value: "down",
options: "up|down|left|right"
}
}
},
这是一个名为层
的对象的对象。
在层
对象中的函数中,我向空的实体
对象添加新数据(实体)
if (!this.entities[which])
{ this.entities[which] = []; }
if (!this.entities[which][id])
{ this.entities[which][id] = {}; }
this.entities[which][id].pos = "0,0";
this.entities[which][id].variables = {};
this.entities[which][id].variables = this.template[which];
因此,稍后当我尝试更改this.entities[which][id].variables.width
时,例如,拥有的相同模板的每个实体都会获得相同的属性以及不会在代码中任何地方更改的模板对象。我调试了几乎所有的东西,并检查了代码的每一部分。实体id也是唯一的
对象发生更改的部分如下所示:
input.setAttribute(“onkeyup”、“layers.entities['”+i+“'][“+j+”].variables['“+jj+”]=this.value;layers.updateEntities();”代码>
其中i是实体的名称,j是id,jj是选项名称
您可以在此处亲自尝试:
[删除]
切换到实体层,添加两个触发器,拖动一个,右键单击它并更改其中一个属性。两者都将更改,尽管它们具有不同的id。新的也会有这些属性
因为模板本身被更改了,我想,这个this.entities[which][id].variables=this.template[which]代码>以某种方式将这两个对象链接在一起,而不是将“副本”指定给左侧变量。不过,我从来没有听说过类似的事情。Javascript中的对象是通过引用传递的,因此您正确地怀疑问题在于每个人共享同一组变量:
var a = {x:1};
var b = a;
b.x = 2;
console.log(a.x); //gives 2
修复代码的方法有很多,但一个非常简单的方法是让模板成为“构造函数”函数,而不是直接返回对象
template: {
trigger: function(){
//now we return a brand new object each time.
return {
width: 32,
height: 32,
delay: 0
};
},
player: function(){ /*...*/},
apple: function(){ /*...*/}
}
//...
this.entities[which][id].variables = this.template[which]();
//^^^
啊,有趣,我不知道。谢谢!:)