jQuery.extend()深拷贝不能像我预期的那样工作?

时间:2016-08-18 16:44:12

标签: jquery extends

我正在使用jQuery测试深层副本,我得到一个空对象而不是正确的副本。

但函数loop2按预期复制(作为参考传递)。

loop也不会获得扩展/合并对象的引用吗?

为什么不通过正确的?

var obj1 = { hello: { f: 1 } };
var obj2 = {};

function loop(original, copy) {
    copy = $.extend(true, {}, original);
    console.log(copy);
}

function loop2(original, copy) {
    $.extend(true, copy, original);
    console.log(copy);
}

function run() {
    loop(obj1, obj2);
    console.log(obj2);

    loop2(obj1, obj2);
    console.log(obj2);
}

输出:

Object {hello: Object}
Object {}  ---> why this one did not get the correct content?
Object {hello: Object}
Object {hello: Object}

1 个答案:

答案 0 :(得分:0)

这是因为在循环函数中,您正在创建新对象并将其分配给函数范围内的局部变量。不修改与其关联的全局变量和对象。此行为未与jQuery.extend()相关联,并且在没有它的情况下也会如此:

var obj2 = {};

function loop(copy) {
  copy = 'a'; //new value assigned, not its reference
  console.log(copy); //a
}

loop(obj2);
console.log('->', obj2); //{}
//it is OK. Its reference was not touched

function loop2(copy) {
  copy.a = 'a'; //added a new property to its reference
  console.log(copy); //{ a: 'a' }
}

loop2(obj2);
console.log('->', obj2); //{ a: 'a' }
//it is OK. Its reference was touched