深拷贝

149 阅读1分钟

方法一 序列化与反序列化

// .1--不支持 函数、正则、Date、undefined
let obj = { name: 'aaa' };

let objnew = JSON.parse(JSON.stringify(obj));
console.log(obj, objnew, obj === objnew);

方法二 递归

function deepClone(obj, hash = new WeakMap()) {
    if (obj == null) return obj;
    // string bool symbol number
    if (typeof obj !== 'object') return obj;
    // 特殊类型
    if (obj instanceof Date) return new Date(obj);
    if (obj instanceof RegExp) return new RegExp(obj);
    // 函数一般不拷贝
    //if (obj instanceof Function) return new Function(obj.toString());
    // 只剩下 [] /{}
    // 防止出现 a.self=a; 
    let val = hash.get(obj);
    if (val) return val;
    let cloneObj = new obj.constructor();
    hash.set(obj, cloneObj);
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            cloneObj[key] = deepClone(obj[key], hash);
        }
    }
    return cloneObj;
}

let obj = { name: '123', age: { a: 1 } }
obj.self = obj;
let obj1 = deepClone(obj);
console.log(obj, obj1, obj === obj1);
obj.age = 12;
console.log(obj, obj1, obj === obj1);