javascript对象深拷贝

52次阅读

共计 440 个字符,预计需要花费 2 分钟才能阅读完成。

function deepCopy(obj){const copy = Object.create(Object.getPrototypeOf(obj));
    var keys = Object.getOwnPropertyNames(obj);

    keys.forEach(key => {const descriptor = Object.getOwnPropertyDescriptor(obj, key);
        if (Object.prototype.toString.call(descriptor.value) === "[object Object]") {descriptor.value = deepCopy(descriptor.value)
        }
        Object.defineProperty(copy, key, descriptor);
    })
    return copy
}

var obj = {a: {b: 666} };
var copyObj = deepCopy(obj);
console.log(copyObj); // {a: {b: 666} }

正文完
 0