var Assertion = function() {
return { "dummy": "data" };
}
Object.defineProperty(Object.prototype, 'should', {
set: function(){},
get: function(){
return new Assertion(this);
}
});
// Insert magic here.
// This needs to be false
console.log(({}).should === undefined);
What options do I have in ES5 to undo a defineProperty call ?
No silly suggestions like Object.defineProperty = function() { } please.
The following Object.defineProperty(Object.prototype, 'should', {})
does not work
and Object.defineProperty(Object.prototype, 'should', { value: undefined })
Throws a Uncaught TypeError: Cannot redefine property: defineProperty in V8
Object.defineProperty(Object.prototype, 'should', {
set: function() {},
get: function() { return undefined; }
});
Throws the same error
delete Object.prototype.should also does not work
In general, you can’t undo a
definePropertycall, since there’s no undo stack or something. The JS engine does not keep track of previous attribute descriptors.For example,
What you can do is remove or reconfigure an attribute, or overwrite its value. As mentioned in the other answer, the
configurableflag is required to betrueif you want to remove or reconfigure.Once a property is defined with
configurable:false, you cannot change theconfigurableflag.To remove an attribute (this is supposedly what you want to do), use
delete:To reconfigure, use
definePropertyagain and pass a different descriptor:As shown in this sample, you can use
definePropertyto switch between accessor (get/set) and data (value) properties.To overwrite, use simple assignment. In this case, you need the
writableflag to betrue. Obviously this does not work with accessor properties. It even throws an exception:Note that
writabledefaults tofalsewhen you usedefineProperty, buttruewhen you use the simple syntaxo.attr = val;to define a (previously not existing) property.