Tengo texto de conjunto de registros y se activa 3 veces, ¿por qué? ver comportamiento aquí 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();En realidad, se llama más de 3 veces. Es una llamada recursiva.
Primero se inicializa en el controlador de promesa usando this.text = response . Luego, dentro del setter llamas this.text = text que básicamente activa el mismo setter una vez más. Y así continúa indefinidamente (limitado por la pila V8 y se produce un error de desbordamiento de pila).
Cuando se utilizan setters, se crean nuevos accesorios para almacenar el valor, porque el nombre de un getter/setter no puede ser el mismo que el que almacena el valor.
Entonces su código debe ser modificado. Hay dos maneras. El anterior usando un guión bajo para decir que es un accesorio privado y no debe usarse directamente desde el exterior.
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();Y uno nuevo que usa la nueva sintaxis de propiedades privadas reales introducida en JS recientemente
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();