1
我一直在寻找Web,发现了一些解决方案,但并不是一个容易实现的ES6 Class中的动态设置器解决方案。使用ES6类的动态Getters/Setters
我想要的是在我的课堂里有一个动态设置器,这样当我从外部添加任何可能的属性时,该属性就会发生某种操作。我读过代理,这似乎是合理的解决方案。但是,我无法理解如何正确实现它,并希望你们的人对此有所贡献。
谢谢!
我一直在寻找Web,发现了一些解决方案,但并不是一个容易实现的ES6 Class中的动态设置器解决方案。使用ES6类的动态Getters/Setters
我想要的是在我的课堂里有一个动态设置器,这样当我从外部添加任何可能的属性时,该属性就会发生某种操作。我读过代理,这似乎是合理的解决方案。但是,我无法理解如何正确实现它,并希望你们的人对此有所贡献。
谢谢!
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
查看http://stackoverflow.com/q/32622970/218196关于它如何完成的例子。 tl; dr:将代理应用于构造函数中新创建的实例。 –
是的!非常感谢 – RonH