3
我正在使用jQuery(1.11.2)和$ .extend克隆对象。这不符合预期。使用jQuery.extend以自定义对象作为属性的意外行为
我有一个源对象包含两个属性与自定义实例的功能(新功能...)作为值。这些值似乎被复制为引用,我期望它们被复制为值。请参阅下面的代码。
var AnyObj = function(){
this.attribute = "anyAttribute";
};
var target = {
a: new AnyObj(),
b: new AnyObj()
}
//this prints "anyAttribute"
console.log(target.a)
//now I create a deep copy
var copy = $.extend(true, {},target);
//and I change the attribute of the COPY(!!!)
copy.a.attribute = "YAYA";
//this prints an object with the value YAYA
console.log(copy.a)
//this should NOT print an object with the value YAYA
console.log(target.a)
^^ 如果我使用{A:{属性: 'V'}},而不是{A:新AnyObj()}它的工作原理。 – Christian 2015-03-31 09:38:23
看到我的编辑... – Christian 2015-03-31 09:43:54
当你传递一个包含2个对象'(a和b)'的对象时,所以每当你改变该对象时,它只会更新实际的对象,如果你想看到这种差异,然后尝试'var copy = $ .extend(true,{},target.a);'只传递该类的一个对象。 – 2015-03-31 09:48:20