This is my base object:
let resources = {
TEST_FLAG: false,
FRUIT: 'banana',
ID: 11
};
I would like to access each property of that object through a setter and a getter. I attempt to do that below:
let dynamicResources = resources
for (let key in resources) {
Object.defineProperty(dynamicResources, key, {
get() {
console.log(`[debug]: GET <${key}>, VALUE <${this[key]}>`);
return `${this[key]}`;
},
set(value) {
console.log(`[debug]: SET <${key}>, VALUE <${this[key]}>`);
this[key] = value;
}
});
}
The idea is that the getter and setter can be generated from a base object with arbitrary number of properties.
When I console.log() the resulting object I get this:
{
TEST_FLAG: [Getter/Setter],
FRUIT: [Getter/Setter],
ID: [Getter/Setter]
}
Which is an indication that the factory loop has worked. However, when I do this:
dynamicResources.FRUIT = 'berry';
I get the following error:
set: function set(value) {
RangeError: Maximum call stack size exceeded
which is an indication that the nested functions are somewhat malformed.
How can I generate a dynamic getter/setter object based on a generic base object?
this[key] = valuestatement from the setter calls the setter function again. To fix that, store and retrieve the value to/from a different property.foo.ID = 33,foo.FRUIT = 'orange',foo.TEST_FLAG = false.setterandgetteraccess points, I would like to generate them with a factory function. So if there are other properties, those will havesetterandgetterfunctionality as well.