I’m receiving maximum call stack size exceeded error on 2 identical defined classes, execept 1 is defining this.name and the other this._name. What is the difference in the 2 classes that’s causing one of them to return a class stack error?
class User {
constructor(name) {
// invokes the setter
this.name = name;
}
get name() {
return this._name;
}
set name(value) {
if (value.length < 4) {
console.log("Name is too short.");
return;
}
this._name = value;
}
}
let user = new User("John");
console.log(user.name); // John
user = new User(""); // Name is too short.
RangeError: Maximum call stack size exceeded
class User {
constructor(name) {
// invokes the setter
this.name = name;
}
get name() {
return this.name;
}
set name(value) {
if (value.length < 4) {
console.log("Name is too short.");
return;
}
this.name = value;
}
}
let user = new User("John");
console.log(user.name); // John
user = new User(""); // Name is too short.
2
Answers
I believe this act as an infinite recursive function ..
When you call
It just endlessly call the getter.
Same thing happening for the setter ..
The first class defines
this._name
as a data property.When the constructor sets
this.name
, it is passed to the Setter, which sets the value ofthis._name
to the value. When the getter is called now, it returns the value ofthis._name
, which was set by the setter earlier.The second class only defines a getter and a setter for
this.name
.When the constructor attemts to set
this.name
to a value, the setter will also try to setthis.name
, which causes the setter to invoked, and the new instance of the setter is attempting to modifythis.name
again, and then the maximum recursion limit is exceeded like this. Same goes for the getter in the second class. It returnsthis.name
thereby invoking itself, and this way, it fills up the stack to the maximum recursion limit.