DEV Community

Aju Chacko
Aju Chacko

Posted on

Object.defineProperty call replaces the setter with a normal data property.

set prop1(name) {
  console.log('Hey there!');
}

Object.defineProperty(obj, 'prop1', {
  value: 'secret',
  writable: true,
  configurable: true,
  enumerable: true
});
Enter fullscreen mode Exit fullscreen mode

This call overwrites the prop1 accessor property with a data property. That means the setter is gone.

Now obj.prop1 is just a string "secret" (and later "hello"), so assigning a new value simply sets the value — no function is called.

In addition, Object.defineProperty() uses the [[DefineOwnProperty]] internal method, instead of [[Set]], so it does not invoke setters, even when the property is already present.

Top comments (1)

Collapse
 
nevodavid profile image
Nevo David •

Neat how using Object.defineProperty just wipes out the setter like flipping a switch. Makes me wonderhow do you know when to keep a function around and when to just use plain old data?