乐趣区

javascript对象深拷贝

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} }
退出移动版