Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda