Cloning A JavaScript Object - Including Getters and Setters

北城以北 提交于 2019-12-05 18:02:31

At a practical level it's impossible to 100% accurately clone an object since the getters and setters (and indeed other functions) may be accessing lexically-scoped private variables via closures. Accessing such a method will reference the original object, not the clone.

If (and only if) that's not the case, you can just enumerate over all properties (even non-enumerable ones) found via Object.getOwnPropertyNames() and then for each name simply obtain the individual PropertyDescriptors with Object.getOwnPropertyDescriptor and then pass the resulting field to Object.defineProperty, e.g.:

function shallowClone(obj) {
    var clone = Object.create(Object.getPrototypeOf(obj));

    var props = Object.getOwnPropertyNames(obj);
    props.forEach(function(key) {
        var desc = Object.getOwnPropertyDescriptor(obj, key);
        Object.defineProperty(clone, key, desc);
    });

    return clone;
}

In ES2017 you can do this instead:

function shallowClone(obj) {
    return Object.create(
        Object.getPrototypeOf(obj), 
        Object.getOwnPropertyDescriptors(obj) 
    );
}

by @Alnitak, I thinks that is shortcut way

function shallowClone(obj){
 var clone = Object.create(Object.getPrototypeOf(obj));
 var descriptors = Object.getOwnPropertyDescriptors(obj);
 Object.defineProperties(clone, descriptors);
 return clone;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!