我陷入了一个奇怪的问题,然后这个问题面临一个挑战,即要理解Angular为何会这样,在Google上搜索该问题并没有太多运气,所以我在这里。
我想测试setInterval()
函数并计数一些变量,而不是太难的东西,而我陷入无法找到解决方案或解释的问题。
这是我正在使用的代码,它可以正常工作:
public counter: number = 1;
myFunction() {
setInterval(() => {
console.log(this.counter);
this.counter++;
}, 1000);
}
Output: 1, 2, 3, 4, 5...
这段代码可以正常工作,但是当我使用这样的函数时,我得到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...
我想变量访问存在一些问题,即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 ...
这是一个非常棘手的主题,所以
首先检查这个问题。如何在回调中访问正确的“ this”?
现在绑定方法-Function.prototype.bind():
(来自文档)
该
bind()
方法创建一个新函数,该函数在被调用时将其this关键字设置为提供的值,并在调用新函数时提供给定的参数序列。
并喜欢这种删除方式(取自docs中的Examples部分):
最简单的用法
bind()
是创建一个函数,无论该函数如何调用,都将使用特定this
值来对其进行调用。对于新的JavaScript程序员来说,一个常见的错误是从对象中提取一个方法,然后再调用该函数并期望它使用原始对象作为其对象
this
(例如,在基于回调的代码中使用该方法)。但是,如果没有特别注意,通常会丢失原始对象。使用原始对象从函数创建绑定函数可以很好地解决此问题
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句