Mos*_*eli 2 javascript scope function-pointers callback setinterval
我陷入了一些奇怪的问题,然后这个问题很难理解为什么 Angular 会这样,在谷歌搜索这个问题没有多少运气,所以我在这里。
我想测试setInterval()函数并计算一些变量,而不是太难的东西,但我陷入了无法找到解决方案或解释的问题中。
这是我正在使用的代码,它工作正常:
public counter: number = 1;
myFunction() {
setInterval(() => {
console.log(this.counter);
this.counter++;
}, 1000);
}
Output: 1, 2, 3, 4, 5...
Run Code Online (Sandbox Code Playgroud)
这段代码工作正常,但是当我把函数变成这样时,我得到 undefined 作为输出,然后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...
Run Code Online (Sandbox Code Playgroud)
我猜变量访问存在一些问题,即 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 ...
Run Code Online (Sandbox Code Playgroud)
现在使用绑定的代码: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 ...
Run Code Online (Sandbox Code Playgroud)
这是一个非常棘手的主题所以
首先检查这个问题如何在回调中访问正确的“this”?
现在绑定方法 - Function.prototype.bind():
(来自文档)
该
bind()方法创建一个新函数,该函数在调用时将其 this 关键字设置为提供的值,并在调用新函数时在任何提供的参数之前提供给定的参数序列。
并且喜欢这个 expletetion(取自文档中的示例部分):
最简单的用法
bind()是创建一个函数,无论它如何调用,都使用特定this值调用。JavaScript 新手的一个常见错误是从对象中提取一个方法,然后稍后调用该函数并期望它使用原始对象作为它的对象
this(例如,通过在基于回调的代码中使用该方法)。然而,如果没有特别注意,原始对象通常会丢失。从函数中创建一个绑定函数,使用原始对象,巧妙地解决了这个问题