I define an object property with Object.defineProperty
. But then how can I unset it?
I tried to unset it with delete foo.bar
(where bar
is the property), but it seems it doesn't work:
var foo = {};
Object.defineProperty(foo, "bar", {
get: function () {
console.log("first call");
delete foo.bar;
var value = 3;
foo.bar = value;
return value;
}
, writeable: true
, enumerable: true
});
console.log(foo.bar);
console.log(foo.bar);
Output is:
first call
3
first call
3
I expected the following output:
first call
3
3
The idea is that after the first get
I want to replace the property with a value.
How can this be done?
Passing the configurable
option to defineProperty
function, fixes the issue:
var foo = {};
Object.defineProperty(foo, "bar", {
get: function () {
console.log("first call");
delete foo.bar;
var value = 3;
foo.bar = value;
return value;
}
, writeable: true
, enumerable: true
, configurable: true
});
console.log(foo.bar);
console.log(foo.bar);
Output:
first call
3
3
From documentation:
configurable
true
if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.Defaults to
false
.