Last active
August 29, 2015 13:57
-
-
Save slikts/9582952 to your computer and use it in GitHub Desktop.
Object cloning using property descriptors
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
function clone(obj, deep) { | |
if (!(obj instanceof Object)) { | |
return obj; | |
} | |
var descriptors = {}; | |
Object.getOwnPropertyNames(obj).forEach(function(name) { | |
var prop = Object.getOwnPropertyDescriptor(obj, name); | |
if (deep) { | |
prop.value = clone(prop.value); | |
} | |
descriptors[name] = prop; | |
}); | |
return Object.create(Object.getPrototypeOf(obj), descriptors); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment