Created
June 25, 2015 13:51
-
-
Save pbakondy/e27b08f20cc34c730355 to your computer and use it in GitHub Desktop.
Copy JS object in ES5 way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I added this sanity check:
Otherwise
getPrototypeOf
will fail, and the input was not always guaranteed to be an object.