-1

I want to configure object via constructor, like that:

class Foo {
  constructor(obj) {
    this.options = {};
    Object.entries(obj).forEach(([key, val]) => {
      const desc = Object.getOwnPropertyDescriptor(this, key);
      if (desc && desc.set) {
        // can't reach that condition
        this[key] = val;
      } else {
        // all properties sets via that condition
        this.options[key] = val;
      }
    });
  }
  set bar(val) {
    this.options.bar = val.toString();
  }
  set baz(val) {
    this.options.baz = parseInt(val, 10);
  }
}

const f = new Foo({ bar: 10, baz: '20', xxx: 0 });
console.log(f.options);
// expected: { bar: '10', baz: 20, xxx: 0 }
// actual { bar: 10, baz: '20', xxx: 0 }

Is it possible to make it works? All properties sets via this.options[key], but I expect that bar and buz should be set via this[key]`.

ZhukovRA
  • 506
  • 1
  • 3
  • 17
  • Hi, @CertainPerformance. I've updated my question to be more specific. – ZhukovRA Jul 06 '18 at 08:23
  • See other dupe - `getOwnPropertyDescriptor` doesn't work because the setter is on the *prototype*, not the instantiated object (`this`) itself. Use `const desc = Object.getOwnPropertyDescriptor(Foo.prototype, key);` – CertainPerformance Jul 06 '18 at 08:30

1 Answers1

2

I think the syntax to do this would be (untested)

this[key] = val;
martincarlin87
  • 10,848
  • 24
  • 98
  • 145