setTimeout() 在 JavaScript 类中使用“this”

IT技术 javascript oop closures
2021-01-21 15:50:48

我正在尝试setTimeout()在 JavaScript 中的类函数中使用。setTimeout()应该引发在同一类的另一种方法,所以我向它传递函数写成window.setTimeout("this.anotherMethod", 4000)这带来了问题:this引用调用对象,在setTimeout()的情况下window. 如何使用附件返回对类对象本身的引用?

myObject = function(){

this.move = function(){
    alert(this + " is running");
}
this.turn = function(){
    alert(this + " is turning");
}
this.wait = function(){
    window.setTimeout("this.run" ,(1000 * randomNumber(1,5)));
}

this.run = function(){
    switch(randomNumber(0,2)){
        case 0:
            this.move();
        break;
        case 1:
            this.turn();
        break;
        case 2:
            this.wait();
    }
}

}

6个回答

你可以这样做:

 var that = this;
 setTimeout(function () {
     that.doStuff();
 }, 4000);

您还可以bind使用更简洁的代码(正如@Raynos 最初指出的那样):

setTimeout(this.doStuff.bind(this), 4000);

bind是完全用于此编码模式(即按this词法捕获的标准库函数

@Antoine:很公平,现在 ES5 支持可能已经足够广泛,使用它完全不是问题。我会在一个注释中编辑。
2021-03-31 15:50:48
我在一个单例模式实现的类中使用了这个答案,并且它有效!
2021-04-01 15:50:48
@Dorward 在编辑答案之前发表了评论。现在是正确的
2021-04-06 15:50:48
@David Dorward:我在点击提交后才意识到这一点。我不应该在早上 5 点发帖。
2021-04-07 15:50:48
我一直被困在这个问题上,这似乎解决了我的问题。谢谢。
2021-04-08 15:50:48

您还可以将函数绑定到作用域。

setTimeout(this.run.bind(this) ,(1000 * randomNumber(1,5)));

注意Function.prototype.bind是 ES5

2021-04-03 15:50:48

this 正如您所发现的,在 javascript 中可能有问题。

我通常通过this在对象内部设置别名来解决这个问题,这样我就可以在需要引用回包含对象时使用别名。

MyObject = function ()
{
    var self = this;

    // The rest of the code goes here

    self.wait = function(){
        window.setTimeout(self.run ,(1000 * randomNumber(1,5)));
    }
}
好吧,这只是一个示例,您可以将其称为 MyObjRef,或者您认为应该使用的任何其他名称。关键是它为您提供了一种获取对象引用的方法。
2021-03-25 15:50:48
我发现self这是一个最具误导性的标识符,尤其是因为它具有非常相似的含义this,正如您指出的那样,意味着其他含义。
2021-04-03 15:50:48
class A{

   setTimeout(()=>{

       // here this != undefined because of arrow function

  },500);

}
在回答旧问题时,如果您包含一些上下文来解释您的答案如何提供帮助,您的答案对其他 StackOverflow 用户会更有用,特别是对于已经有公认答案的问题。请参阅:我如何写出一个好的答案
2021-04-09 15:50:48
this.wait = function(){
    var self = this;
    window.setTimeout(function() { self.run() } ,(1000 * randomNumber(1,5)));
}

因此,您将调用 .run 的对象的引用存储在局部变量 ('self') 中。