Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Field, getter and setter with the same name

Tags:

javascript

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");
like image 417
Alexey Galanov Avatar asked Feb 13 '16 13:02

Alexey Galanov


People also ask

Can getter and setter have the same name?

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.

What should I name my 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.

What is @getter and @setter in spring boot?

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.

How do you use setters and getters in two different classes?

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 .


1 Answers

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.

like image 107
Jeroen Avatar answered Sep 18 '22 05:09

Jeroen