2016-08-16 56 views
1

我一直在尋找Web,發現了一些解決方案,但並不是一個容易實現的ES6 Class中的動態設置器解決方案。使用ES6類的動態Getters/Setters

我想要的是在我的課堂裏有一個動態設置器,這樣當我從外部添加任何可能的屬性時,該屬性就會發生某種操作。我讀過代理,這似乎是合理的解決方案。但是,我無法理解如何正確實現它,並希望你們的人對此有所貢獻。

謝謝!

+1

查看http://stackoverflow.com/q/32622970/218196關於它如何完成的例子。 tl; dr:將代理應用於構造函數中新創建的實例。 –

+0

是的!非常感謝 – RonH

回答

-3
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