Skip to content

Instantly share code, notes, and snippets.

@kangax
Created August 13, 2010 04:53
Show Gist options
  • Save kangax/522313 to your computer and use it in GitHub Desktop.
Save kangax/522313 to your computer and use it in GitHub Desktop.
// More convenient modification of ES5 property descriptors (by @kangax)
Object.changeDesc = function(obj, prop, newDesc) {
var oldDesc = Object.getOwnPropertyDescriptor(obj, prop);
for (var p in newDesc) {
if (p === 'get' || p === 'set') {
delete oldDesc.value;
delete oldDesc.writable;
}
else if (p === 'value' || p === 'writable') {
delete oldDesc.get;
delete oldDesc.set;
}
oldDesc[p] = newDesc[p];
}
Object.defineProperty(obj, prop, oldDesc);
};
// Examples:
var o = { x: 1 };
Object.changeDesc(o, 'x', { get: function(){ } }); // o.x is now an accessor with no setter
Object.changeDesc(o, 'x', { value: 2 }); // o.x is back to a data property with another value
Object.changeDesc(o, 'x', { enumerable: false }); // o.x's enumerable attribute is now false
Object.changeDesc(o, 'x', { set: function(){ return 'boo' }, enumerable: true }); // o.x is accessor again, with a setter and enumerable attribute set to `true`
// etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment