Reputation: 10250
I have a object like below , when a property root
is defined on this object , i want the property to be modified, so i have the following code:
html = {};
and then i use Object.defineproperty()
like so:
Object.defineProperty( html , 'root' , {
set ( val ) {
html.root = `${val} i got the power`
}
});
Now when i try the following:
html.root = 'James !!';
I get an error saying :
Uncaught RangeError: Maximum call stack size exceeded
Why am i unable to add this property root
with the modification.
Upvotes: 0
Views: 559
Reputation: 138477
html.root =
will call the setter itself, wich will call the setter itself, which ...
You can't have a setter and its backing field under the same name, use a different field (e.g. html._root
) to store the underlying value.
Upvotes: 3
Reputation: 122087
You create infinite loop with set
method because inside you try to set property with same name so the same set method is called.
You can fix this by using get
method and inside set
method you use some other key name (for example original key + some prefix _
).
const html = {};
Object.defineProperty(html, 'root', {
set(val) {
html._root = `${val} i got the power`
},
get() {
return html._root
}
});
html.root = 'James !!';
console.log(html.root)
Upvotes: 3