4

I've been searching the web and found some solutions but not an easy to implement solution for dynamic setters in an ES6 Class.

What I'd like is to have is a dynamic setter inside my class so that when I add any possible property from the outside, a certain operation will occur on that property. I've read on Proxies and that does seem to be the reasonable solution for this. However, I wasn't able to understand how to correctly implement it and would like your guys' input on this.

Thanks!

RonH
  • 357
  • 2
  • 14

1 Answers1

-1
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
novrm
  • 29
  • 1