gpt4 book ai didi

JavaScript - 带有传递函数的 setInterval 无法识别全局变量

转载 作者:行者123 更新时间:2023-11-29 16:39:11 25 4
gpt4 key购买 nike

我被困在一些奇怪的问题中,然后这个问题在理解为什么 Angular 会这样表现时遇到了挑战,运气不好在 Google 上搜索这个问题,所以我来了。

我想测试 setInterval() 函数并计算一些变量,不是太难的东西,但我遇到了无法找到解决方案或解释的问题。

这是我正在使用的代码,它运行良好:

public counter: number = 1;

myFunction() {
setInterval(() => {
console.log(this.counter);
this.counter++;
}, 1000);
}

Output: 1, 2, 3, 4, 5...

这段代码工作正常,但是当我将函数变成这样时,输出未定义,然后是 Nan, Nan, Nan

public counter: number = 1;

foo() {
console.log(this.counter);
this.counter++;
}

myFunction() {
setInterval(this.foo, 1000);
}

* myFunction is the starting function *

Output: undefined, Nan, Nan, Nan...

我猜 foo() 无法访问全局变量的变量访问存在一些问题,但这是怎么发生的?我该如何解决这个问题?

最佳答案

这里有一段代码可以按照你描述的那样运行

 class A{
public counter: number = 1;

foo() {
alert(this.counter);
this.counter++;
}

myFunction() {
setInterval(this.foo, 1000);
}
}

const a = new A();
a.myFunction(); // output andefined, Nan, Nan ...

现在使用 bind 的代码:JSFiddle

 class A{
public counter: number = 1;

foo() {
alert(this.counter);
this.counter++;
}

myFunction() {
setInterval(this.foo.bind(this), 1000);
}
}

const a = new A();
a.myFunction(); // output 1, 2, 3, 4 ...

这是一个非常棘手的问题,所以

先查这个问题How to access the correct 'this' inside a callback?

还有几个关于这个主题的非常好的答案 herehere .


现在是绑定(bind)方法 - Function.prototype.bind() :

(来自文档)

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

并喜欢这个词(摘自 docs 中的示例部分):

The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value.

A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g. by using that method in callback-based code). Without special care, however, the original object is usually lost.

Creating a bound function from the function, using the original object, neatly solves this problem

关于JavaScript - 带有传递函数的 setInterval 无法识别全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48254716/

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