Skip to content

Latest commit

 

History

History
51 lines (39 loc) · 981 Bytes

File metadata and controls

51 lines (39 loc) · 981 Bytes

30、如何克隆一个Object对象?

?> 此题也就是深拷贝,就像jQueryextend方法

var obj = {
    a: 1,
    b: 2,
    c: {
        d: 3
    }
}

# 浅拷贝
var c1 = $.extend({}, obj);
console.log(c1.a === obj.a);  // true

//深拷贝
var c2 = $.extend(true, {}, obj);
console.log(c2.a === obj.a);  //false

官方答案

var obj = {a: 1 ,b: 2}
var objclone = Object.assign({},obj);// 指向不同的对象到对象
let obj = {
    a: 1,
    b: 2,
    c: {
        age: 30
    }
};

var objclone = Object.assign({},obj);
console.log('objclone: ', objclone);

obj.c.age = 45;
console.log('After Change - obj: ', obj);           // 45 - This also changes
console.log('After Change - objclone: ', objclone); // 45

参考资料:

题目来源

MDN: Object.assign()