我一直在网上搜索并找到了一些解决方案,但不是一个易于在 ES6 类中实现动态 setter 的解决方案。
我想要的是在我的类中有一个动态 setter ,这样当我从外部添加任何可能的属性时,该属性就会发生特定的操作。我读过 Proxies,这似乎是一个合理的解决方案。但是,我无法理解如何正确实现它,并希望你们对此提出意见。
谢谢!
最佳答案
let property_one = 'one';
let property_two = 'two';
/**
* ConfigurationClass class.
*/
class ConfigurationClass
{
/**
* Constructor.
*
* Create instance.
*/
constructor(config = {
'property_one' : property_one,
'property_two' : property_two,
})
{
this.__proto__ = new Proxy(config, {
get: (container, property) => (property in container) ? container[property] : undefined,
set: (container, property, value) => (container[property] = value) ? true : true
});
}
};
let configurationClass = new ConfigurationClass();
console.log(configurationClass.property_one); // one
console.log(configurationClass.property_two); // two
console.log(configurationClass.property_three); // undefined
关于带有 ES6 类的动态 getter / setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38978417/