John Smith
John Smith

Reputation: 1780

Setter/getter for class property (Object.assign)?

I'm trying to be trigger a setter on a class property:

class Example {
    prop = { default: 'default', color: 'red' };

    set prop(value) {
        // this.prop will be undefined as the setter overrides the class property)
        Object.assign(this.prop, value);
    }
}

const myExample = Example();
myExample.prop.default = 'new';

// Trying to get prop = { default: 'new', color: 'red' }

The setter will override prop I believe, how could I specify a default object value? Should I store the class property prop as like _prop?

Upvotes: 0

Views: 1153

Answers (1)

Oriol
Oriol

Reputation: 288020

I would define the accessors manually in the constructor:

class Example {
  constructor() {
    var prop = { default: 'default', color: 'red' };
    Object.defineProperty(this, 'prop', {
      get() { return prop; },
      set(value) { Object.assign(prop, value); }
    });
  }
}
const myExample = new Example();
console.log(myExample.prop);
myExample.prop = {foo: "bar"};
console.log(myExample.prop);

If you don't mind prop being public, you could move the accessors outside the constructor, and share them among all instances:

class Example {
  constructor() {
    this._prop = { default: 'default', color: 'red' };
  }
  get prop() { return this._prop; }
  set prop(value) { Object.assign(this._prop, value); }
}
const myExample = new Example();
console.log(myExample.prop);
myExample.prop = {foo: "bar"};
console.log(myExample.prop);

Upvotes: 2

Related Questions