Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

es6实现深拷贝 #18

Open
yaogengzhu opened this issue Sep 15, 2021 · 1 comment
Open

es6实现深拷贝 #18

yaogengzhu opened this issue Sep 15, 2021 · 1 comment

Comments

@yaogengzhu
Copy link
Owner

yaogengzhu commented Sep 15, 2021

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
Copy link
Owner Author

补充知识点

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

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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant