gpt4 book ai didi

javascript - 了解 "this"在两种不同上下文中的使用

转载 作者:行者123 更新时间:2023-12-03 00:56:57 28 4
gpt4 key购买 nike

我不明白为什么“this”在这种情况下返回“NaN”:

function Counter() {
this.num = 0;
this.timer = setInterval(function add() {
this.num++;
console.log(this.num);
}, 1000);
}

在这个中它指的是“this.value”:

function foo() {
this.value = 'Hello, world';

this.bar = function() {
alert(this.value);
}
}

var inst = new foo();
inst.bar();

我知道在第一种情况下“this”指向 Window 对象,我只是不明白为什么会这样。

最佳答案

setInterval内部,this将是全新的,它不知道Counter。您可以使用 bind 将上下文 this 传递给 setInterval

function Counter() {
this.num = 0;
this.timer = setInterval(function add() {
this.num++;
console.log(this.num);
}.bind(this), 5000);
}

Counter()

或者您也可以使用箭头功能

function Counter() {
this.num = 0;
this.timer = setInterval(() => {
this.num++;
console.log(this.num);
}, 5000);
}

Counter()

关于javascript - 了解 "this"在两种不同上下文中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52786568/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com