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?
Use Proxy constructor. Look to Developer Mozilla Proxy Page
var dynamicObject = new Proxy({
TEST_FLAG: false,
FRUIT: 'banana',
ID: 11
},{
get:function(target,key){
console.log(`get ${key} value. value is: ${target[key]}`);
return target[key]
},
set:function(target,key,val){
console.log(`set ${key} value. old value is:${target[key]} new value is ${val}`)
target[key] = val;
return true;
}
})
console.log(dynamicObject.ID);
dynamicObject.ID = 25;
// Output is:
/*
get ID value. value is: 11
11
set ID value. old value is:11 new value is 25
*/