setTimeout() 在 JavaScript 类中使用“this"; [英] setTimeout() inside JavaScript Class using "this"

查看:30
本文介绍了setTimeout() 在 JavaScript 类中使用“this";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use setTimeout() inside a class function in JavaScript. The setTimeout() is supposed to trigger another method in the same Class, so the function I am passing it is written as window.setTimeout("this.anotherMethod", 4000). That bring the problem: this references the calling Object, in the case of setTimeout() it is window. How can I use enclosures to return a reference to the Class Object itself?

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();
    }
}

}

推荐答案

您可以这样做:

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

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

You can also bind for more succinct code (as originally pointed out by @Raynos):

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

bind 是这个编码模式的标准库函数(即按词法捕获 this).

bind is a standard library function for exactly this coding pattern (ie capturing this lexically).

这篇关于setTimeout() 在 JavaScript 类中使用“this";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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