将本地函数传递给 setTimeout()

Passing local functions to setTimeout()

本文关键字:setTimeout 函数      更新时间:2023-09-26

我写了下面的函数。

function obj()
{
     this.a;
}
obj.prototype.catch = function()
{
    alert('Catched')
}
obj.prototype.do = function()
{
    alert('called');
}

我需要的是,在调用 obj::d o() 后调用 obj::catch(),并且必须从 obj::d o() 内部执行调用那么如何将 obj 的本地函数传递给 setTimeout

我试过了

obj.prototype.do = function()
 { 
     window.setTimeout('"'+this.catch+'()"',1000);
     alert('called');
 }

它不起作用然后我试了

 obj.prototype.do = function()
 { 
     window.setTimeout('"'+this+'.catch()"',1000);
     alert('called');
 }

这在Chrome控制台上给了我以下错误

Uncaught SyntaxError: Unexpected token ILLEGAL

所以我尝试了以下肮脏的方法(它真的很脏吗?

 obj.prototype.do = function()
 { 
     this.pid = randomVal(100);
     window['temp'+this.pid] = this;
     window.setTimeout("temp"+this.pid+".catch();",1000);
     alert('called');
 }
 function randomVal(bound)//returns a random number between 0 and <bound>
 {
       return (Math.floor(Math.random()*(bound)));
 }

这奏效了。

那么为什么前两种方法不起作用。有没有其他方法可以在没有全局变量的情况下做同样的事情..第二种方法和最后一种方法几乎相似。但是为什么我会在第二种方法中得到错误..?工作代码可以在这里找到http://jsfiddle.net/jXhAs/

不要将字符串传递给setTimeout...曾。

var self = this; // Because the scope will change
setTimeout(function () { self.catch() },1000);

或者,如果您使用的是 JS 1.8.5:

setTimeout(this.catch.bind(this),1000);

您可以阅读有关bind的更多信息

你应该将一个函数传递给setTimeout(而不是字符串):

例:

var self = this;
setTimeout(function(){
    self.catch();
},1000);

使用闭包

obj.prototype.do = function()
{ 
     window.setTimeout((function(that){
        return function(){
            that.catch();
        };
     })(this),1000);
     alert('called');
}

为什么要经历所有这些努力,只需传递函数即可。

function obj() {
    this.a;
}
obj.prototype.
catch = function() {
    alert('Catched')
}
obj.prototype.do = function() {
    setTimeout(this.
    catch, 1000);
}
var test = new obj();
test.do();​