2

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?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

2 Answers2

2

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.

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
0

You need to set configurable property to allow delete configurable: true But as best practice, do not mix up data property and accessor property

hjl
  • 2,794
  • 3
  • 18
  • 26