Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jQuery.extend将自定义对象作为属性时出现意外行为_Javascript_Jquery - Fatal编程技术网

Javascript 使用jQuery.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

我正在使用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()错误。有关更多详细信息,请参阅以下内容:

^如果我使用{a:{attribute:'v'}}而不是{a:new AnyObj()}它可以工作。当你传递一个包含另外两个对象的对象时,
(a和b)
,所以每当你改变这个对象时,它只会更新实际对象,如果你想看到这个差异,那么试着
var copy=$.extend(true,{},target.a)仅传递该类的对象。