Skip to content

Instantly share code, notes, and snippets.

@pbakondy
Created June 25, 2015 13:51
Show Gist options
  • Save pbakondy/e27b08f20cc34c730355 to your computer and use it in GitHub Desktop.
Save pbakondy/e27b08f20cc34c730355 to your computer and use it in GitHub Desktop.
Copy JS object in ES5 way
// http://speakingjs.com/es5/ch17.html#code_copyOwnPropertiesFrom
// To create an identical copy of an object, you need to get two things right:
// - The copy must have the same prototype as the original.
// - The copy must have the same properties, with the same attributes as the original.
function copyObject(orig, deep) {
// 1. copy has same prototype as orig
var copy = Object.create(Object.getPrototypeOf(orig));
// 2. copy has all of orig’s properties
copyOwnPropertiesFrom(copy, orig, deep);
return copy;
}
function copyOwnPropertiesFrom(target, source, deep) {
Object.getOwnPropertyNames(source)
.forEach(function(propKey) {
var desc = Object.getOwnPropertyDescriptor(source, propKey);
Object.defineProperty(target, propKey, desc);
if (deep && typeof desc.value === 'object') {
target[propKey] = copyObject(source[propKey], deep);
}
});
return target;
}
@matthew-dean
Copy link

I added this sanity check:

        if (!orig || !orig.prototype) {
            return orig;
        }

Otherwise getPrototypeOf will fail, and the input was not always guaranteed to be an object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment