从Javascript构造函数动态调用setter

时间:2018-07-06 08:00:29

标签: javascript es6-class

我想通过构造函数配置对象,像这样:

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 }

是否有可能使其起作用?所有属性都通过this.options[key]设置,但是我希望barbuz应该通过this [key]`设置。

1 个答案:

答案 0 :(得分:2)

我认为这样做的语法会(未经测试)

this[key] = val;