I'm trying to recursively assign the object values from class constructor argument as a properties of the class. Can't figure out how to do a recursion - getting 'Maximum call stack size exceeded' and infinity loops most of the time. Here is the demo:
const Locale = function(rules) {
for (let prop in rules) {
Object.defineProperty(this, prop, {
get: function () {
console.log('getter for "%s" called', prop)
return rules[prop];
}
});
}
}
const rules = {
a: {
b: {
c: 'value'
}
}
}
const locale = new Locale(rules);
console.log(locale.a.b.c);
Now I'm getting the following console output:
getter for "a" called
value
How to assign a getter for each level of the rules
object? Expected console output:
getter for "a" called
getter for "b" called
getter for "c" called
value
You need to create a Locale
object for each nested level of the rules
object:
const Locale = function(rules) {
for (let prop in rules) {
Object.defineProperty(this, prop, {
get: function () {
console.log('getter for "%s" called', prop);
// create new Locale if object, return value if not an object
if( rules[prop] !== null && typeof rules[prop] === 'object' )
return new Locale( rules[prop] );
else
return rules[prop];
}
});
}
}
const rules = {
a: {
b: {
c: 'value'
}
}
}
const locale = new Locale(rules);
console.log(locale.a.b.c);