使用"this"在JavaScript类中的setTimeout()

Dea*_*ean 36 javascript oop closures

我试图setTimeout()在JavaScript中的类函数内使用.本setTimeout()应该引发在同一类的另一种方法,所以我向它传递函数写成window.setTimeout("this.anotherMethod", 4000).这带来了问题:this引用调用Object,如果是的setTimeout()window.如何使用enclosure返回对Class对象的引用?

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Tik*_*vis 64

你可以这样做:

 var that = this;
 setTimeout(function () {
     that.doStuff();
 }, 4000);
Run Code Online (Sandbox Code Playgroud)

您还可以获得bind更简洁的代码(最初由@Raynos指出):

setTimeout(this.doStuff.bind(this), 4000);
Run Code Online (Sandbox Code Playgroud)

bind是一个标准的库函数,用于完全符合这种编码模式(即从this词汇上捕获).


Ray*_*nos 7

您还可以将函数绑定到范围.

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

警告Function.prototype.bind是ES5

  • 你可以绑定到任何js项目:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind :) (2认同)

Gor*_*onM 6

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)));
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

class A{

   setTimeout(()=>{

       // here this != undefined because of arrow function

  },500);

}
Run Code Online (Sandbox Code Playgroud)

  • 在回答旧问题时,如果您包含一些上下文来解释您的答案如何提供帮助,那么您的答案对其他 StackOverflow 用户会更有用,特别是对于已经有公认答案的问题。请参阅:[如何写出一个好的答案](https://stackoverflow.com/help/how-to-answer)。 (9认同)