Field, getter and setter with the same name

Could you explain why I get

Uncaught RangeError: maximum call stack size

in this example. What is the sequence of actions?

"use strict"; let myClass = class myClass{ constructor(name){ this.name = name; } get name() { return this.name; } set name(name){ this.name = name; } } let myObj = new myClass("John"); 
+5
source share
1 answer

You call the setter from the setter, endlessly looping.

 set name(name) { this.name = name; // <-- `this.name` calls the `set`ter again } 

You should use a type variable with a different name:

 "use strict"; let myClass = class myClass { constructor(name) { this.name = name; } get name() { return this._name; } set name(name) { this._name = name; } } let myObj = new myClass("John"); console.log(myObj); 

To my surprise, it is not trivial for variables to be private to the class .

+2
source

Source: https://habr.com/ru/post/1242953/


All Articles