Created
August 13, 2010 04:53
-
-
Save kangax/522313 to your computer and use it in GitHub Desktop.
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
// 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