yaogengzhu / Learning-notes

基础回顾、笔记
1 stars 0 forks source link

es6实现深拷贝 #18

Open yaogengzhu opened 3 years ago

yaogengzhu commented 3 years ago
function deepClone(origin, hasMap = new WeakMap()) {
    if (typeof origin !== 'object' || origin === null ) {
        return origin;
    }
    if (origin instanceof Date) {
        return new Date(origin);
    }
    if (origin instanceof RegExp) {
        return new RegExp(origin);
    }
    // 解决这个对象重复拷贝问题
    const hasKey = hasMap.get(origin);
    if (hasKey) {
        return hasKey;
    }
    let target = new origin.constructor();
    hasMap.set(origin, target);
    for (let k in origin) {
        // origin.hasOwnProperty(k)
        if (Object.prototype.hasOwnProperty.call(origin, k)) {
            target[k] = deepClone(origin[k], hasMap);
        }
    }
    return target;
}
yaogengzhu commented 3 years ago

补充知识点

借用对象的构造函数,生成一个新的对象

const obj = {a: 1}
console.log(new obj.constructor)
const origin = {};
let target = new origin.constructor();
target.a = 1;
console.log(target); // {a: 1}
console.log(origin); // {}
const origin = [];
let target = new origin.constructor();
target[0] = 1;
console.log(target);
console.log(origin);