使用带有自定义对象作为属性的jQuery.extend时出现意外行为

Unexpected behavior using jQuery.extend with custom objects as attributes

本文关键字:extend jQuery 意外 属性 自定义 对象      更新时间:2023-09-26

我正在使用jQuery(1.11.2)和$.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)

这似乎是一个jQuery extend()错误。有关更多详细信息,请参阅以下内容:http://bugs.jquery.com/ticket/10014