class Person { constructor(name, age) { this.name = name; this.age = age; } set name (value) { this.name = value; } set age (value) { this.age = value; } printName() { console.log(this.name); } printAge() { console.log(this.age); } }
When the class assigns the name and age properties, it calls the setters, which in turn call themselves. This creates an infinite loop and will throw a “Maximum call stack size exceeded” error. To fix this, you should use different names for the properties and the setters.
class Person { constructor(name, age) { this._name = name; this._age = age; } set name (value) { this._name = value; } set age (value) { this._age = value; } get name() { return this._name; } get age() { return this._age; } printName() { console.log(this._name); } printAge() { console.log(this._age); } }