The accepted answer is not correct.
Instance vs prototype
By using Object.defineProperty
you are defining the property on the instance of the class. When you use a getter/setter, the property is set on the prototype.
This means that in your case, Object.hasOwnProperty
will return true
with
Object.defineProperty
and false
with the getter/setter.
class Foo {
constructor () {
Object.defineProperty(this, 'bar', {
get () {
return this._bar;
},
set (value) {
this._bar = value;
this.extraFunctionCall();
}
});
}
get baz () {
return this._baz;
}
set baz (value) {
this._baz = value;
this.extraFunctionCall();
}
}
const myFoo = new Foo();
console.log('bar', myFoo.hasOwnProperty('bar')); // true
console.log('baz', myFoo.hasOwnProperty('baz')); // false
Object.defineProperty use case
Object.defineProperty
is useful when you want to programmatically define more than one property the same way.
For example, I have found it useful when creating Custom Elements because I need to create a lot of properties with the same getter/setter pattern.
class Foo {
constructor() {
const defineProperty = property =>
Object.defineProperty(this, property, {
get() {
/* getter definition */
},
set(value) {
/* setter definition */
},
});
defineProperty('bar');
defineProperty('baz');
}
}
Here I can define a getter/setter for bar
and baz
without having to duplicate the code.
As far as I know, there is no way to do this using the getter/setter syntax.