Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
javascript setter why does it seem to be called 3 times at execution whereas it called only once from constructor?

I have log set text and it is triggered 3 times why ? see behavior here https://jsfiddle.net/5kv2g6hc/

class Test {

  set text(text) {
    console.log(text); // 3 times ?!!!
    this.text = text;
  }
  
  constructor() {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => {
        response.text().then((response) => {
          this.text = response;
          // console.log(this.text);
        });
      });
  }
}

let test = new Test();
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Actually, it's called more than 3 times. It's a recursive call.

It is first initialized in the promise handler by using this.text = response. Then, within the setter you call this.text = text which basically triggers the same setter once again. And so it goes indefinitely (limited by V8 stack and stack overflow error is thrown).

When setters are used new props are created to store the value, because name of a getter/setter cannot be the same as the one storing the value.

So your code should be modified. There are two ways. The old one by using an underscore to tell that it's a private prop and shouldn't be used directly from the outside

class Test {
  set text(text) {
    console.log(text);
    this._text = text; // <- here _text instead of text
  }
  
  constructor() {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => {
        response.text().then((response) => {
          this.text = response;
          // console.log(this.text);
        });
      });
  }
}

let test = new Test();

And a new one which uses the new syntax of real private properties introduced in JS recently

class Test {
  #text; // <- first, declare the private prop

  set text(text) {
    console.log(text);
    this.#text = text; // <- then use #text instead of text
  }
  
  constructor() {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => {
        response.text().then((response) => {
          this.text = response;
          // console.log(this.text);
        });
      });
  }
}

let test = new Test();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!