我有日志集文本,它被触发了3次,为什么?查看此处的行为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();
实际上,它被调用了3次以上。这是一个递归调用
首先在承诺处理程序中使用this.text = response
进行初始化。然后,在setter中调用this.text = text
,这基本上再次触发相同的setter。因此,它无限地运行(受V8堆栈限制,抛出堆栈溢出错误)。
当使用setter时,会创建新的props来存储值,因为getter/setter的名称不能与存储值的名称相同。
所以你的代码应该被修改。有两种方法。旧的使用下划线来告诉它是一个私有的道具,不应该从外部直接使用
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();
和一个新的,它使用了JS中最近引入的真正私有属性的新语法
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();