Could you explain why I get
Uncaught RangeError: Maximum call stack size exceeded
in this example. What's 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");
You can only have one getter or setter per name, on an object. (So you can have both one value getter and one value setter, but not two 'value' getters.) The only way to delete a getter or setter is to do: 'delete object[name];' Be aware, that this command is capable of deleting normal properties, getters and setters.
Given this, getters and setters are also known as accessors and mutators, respectively. The getter method returns the value of the attribute.
Getters and Setters play an important role in retrieving and updating the value of a variable outside the encapsulating class. A setter updates the value of a variable, while a getter reads the value of a variable.
To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B . You can do this e.g. by passing it as a parameter to a method of B , or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter .
You're calling the setter from the setter, infinitely looping.
set name(name) {
this.name = name; // <-- ⛔ `this.name` calls the `set`ter again
}
You should use a differently named backing variable of some sort. Unfortunately the "TC39 Private Fields" proposal for JS is not finalized so they will be public, and a naming convention is needed for now.
Here's a modern example:
class Person {
_name = ""; // 'private' by convention, see also: https://github.com/tc39/proposal-class-fields#private-fields
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
constructor(name) {
this.name = name;
}
}
Or following the Question's structure:
"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's not trivial to have variables private to a class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With