13

I try to define getter and setter in constructor via Object.assign:

function Class() {
  Object.assign(this, {
    get prop() { console.log('call get') },
    set prop(v) { console.log('call set') },
  });
}

var c = new Class(); // (1) => 'call get'
console.log(c.prop); // (2) => undefined
c.prop = 'change';
console.log(c.prop); // (3) => 'change' 

Questions:

(1) Why getter is called?

(2) Why getter isn't called?

(3) Why setter is ignored?

mqklin
  • 1,928
  • 5
  • 21
  • 39

1 Answers1

21

The answer to all three of your questions is the same: Object.assign reads the value of the property from the source object, it doesn't copy getters/setters.

You can see that if you look at the property descriptor:

var source = {
  get prop() { },
  set prop(v) { }
};
console.log("descriptor on source", Object.getOwnPropertyDescriptor(source, "prop"));
var target = Object.assign({}, source);
console.log("descriptor on target", Object.getOwnPropertyDescriptor(target, "prop"));

To define that property on this inside Class, use defineProperty:

function Class() {
  Object.defineProperty(this, "prop", {
    get() { console.log('call get') },
    set(v) { console.log('call set') },
  });
}
var c = new Class();
console.log(c.prop); // => 'call get', undefined
c.prop = 'change'; // => 'call set'
console.log(c.prop); // => 'call get', undefined
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Reversing them works `return Object.assign({ get prop() { console.log('call get') }, set prop(v) { console.log('call set') }}, this); } ` – wmik Nov 04 '20 at 16:58
  • 1
    @wmik - Not really: if you do that, the resulting object won't be an instance of the class, it'll be the raw object you're passing as the first argument to `Object.assign`. – T.J. Crowder Nov 04 '20 at 17:08