在setTimeout中传递this.method不起作用? [英] passing this.method in setTimeout doesn't work?

查看:166
本文介绍了在setTimeout中传递this.method不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现将对象方法作为参数传递给setTimeout时出现问题。
我知道嵌套函数内部,这个需要手动设置,但如果我直接传递函数对象,在我的情况下是this.counting。将匿名函数声明为第一个参数的需要是什么,this.counting已经是一个函数。

I am seeing problem with passing object method as argument to setTimeout. I know inside nested function, scope of this need to be set manually but what if i directly pass function object, in my case this.counting. What is the need of declaring anonymous function as first argument, this.counting is already a function.

Mozilla 还使用函数(msg){self.remind(msg);}而不是thisTime中的setTimeout第一个参数。

Mozilla also uses function(msg) {self.remind(msg);} instead of this.remind inside setTimeout first argument.

function Timer(count,start){
    this.count = count;
    this.start = start;

}

//below code works
Timer.prototype.counting = function(){
    var self = this;
    setTimeout(function(){self.counting();},this.start);
    console.log(this.count);
    this.count++;
};

//below code doesn't work
/*
Timer.prototype.counting = function(){
    setTimeout(this.counting,this.start);
    console.log(this.count);
    this.count++;
};
*/
var t1 = new Timer(0,1000);
t1.counting();
var t2 = new Timer(100,1000);
t2.counting();


推荐答案

setTimeout 的MDN文档有一整节关于它,我建议阅读它。

The MDN documentation of setTimeout has a whole section about it, I recommend to read it.

在回调中你传递给 setTimeout 将引用窗口,而不是您的类的实例。

Inside the callback you pass to setTimeout, this will refer to window, not to the instance of your class.

如果调用该函数, this.count (引用 window.count )将是 undefined ,因为没有全局 count 变量。稍后它会变成 NaN undefined ++ NaN )。对象的 count 属性根本不会改变。

If the function is called, this.count (which refers to window.count) would be undefined, since there is no global count variable. Later it would become NaN (undefined++ is NaN). The count property of your object would not change at all.

通过显式调用函数作为方法对象( self.counting()),确保正确引用您的类的实例。

By calling the function explicitly as a method of the object (self.counting()), you ensure that this correctly refers to the instance of your class.

您可以使用 .bind [MDN] ,而不是使用其他功能:

You could achieve the same by using .bind [MDN], instead of using another function:

setTimeout(this.counting.bind(this), this.start);

阅读此MDN文章了解有关的更多信息。

Read this MDN article to learn more about this.

这篇关于在setTimeout中传递this.method不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆