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]`.