Javascript 使用jQuery.extend将自定义对象作为属性时出现意外行为
我正在使用jQuery(1.11.2)和$.extend克隆一个对象。这不符合预期 我有一个源对象,其中包含两个属性,其中函数的自定义实例(新函数…)作为值。这些值似乎被复制为引用,而我希望它们被复制为值。请参阅下面的代码Javascript 使用jQuery.extend将自定义对象作为属性时出现意外行为,javascript,jquery,Javascript,Jquery,我正在使用jQuery(1.11.2)和$.extend克隆一个对象。这不符合预期 我有一个源对象,其中包含两个属性,其中函数的自定义实例(新函数…)作为值。这些值似乎被复制为引用,而我希望它们被复制为值。请参阅下面的代码 var AnyObj = function(){ this.attribute = "anyAttribute"; }; var target = { a: new AnyObj(), b: new AnyObj() } //this prints "anyAt
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)
这似乎是一个jQuery extend()错误。有关更多详细信息,请参阅以下内容:
^如果我使用{a:{attribute:'v'}}而不是{a:new AnyObj()}它可以工作。当你传递一个包含另外两个对象的对象时,
(a和b)
,所以每当你改变这个对象时,它只会更新实际对象,如果你想看到这个差异,那么试着var copy=$.extend(true,{},target.a)代码>仅传递该类的对象。