mqklin mqklin - 1 month ago 13
Javascript Question

Object.assign getters and setters in constructor

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?

Answer

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

Comments