Skip to content

Instantly share code, notes, and snippets.

@creationix
Created January 12, 2011 17:21
Show Gist options
  • Save creationix/776495 to your computer and use it in GitHub Desktop.
Save creationix/776495 to your computer and use it in GitHub Desktop.
function shallowCopy(old) {
var props = {};
Object.getOwnPropertyNames(old).forEach(function (name) {
props[name] = Object.getOwnPropertyDescriptor(old, name);
});
return Object.create(Object.getPrototypeOf(old), props);
}
// A very hard and dangerous to copy object
var obj = {
get foo() { throw new Error("Boom"); },
set bar(value) { throw new Error("Ouch"); }
}
Object.defineProperty(obj, 'hidden', {value: "Can't see me"});
var clone = shallowCopy(obj);
console.dir(obj);
console.dir(clone);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment