Javascript 在使用setTimeout()时,如何使用call()设置'this'的值?

Javascript 在使用setTimeout()时,如何使用call()设置'this'的值?,javascript,prototype,this,settimeout,Javascript,Prototype,This,Settimeout,我正在用javascript制作一个简单的游戏。以下是我的球员方法(问题部分是在球员落水半秒后调用重置方法): ..这两者都不正确(重置正确但立即执行): 那么如何将设置为player,并使用setTimeout将其传递给reset 你没有call将立即调用该函数,以便将其返回值传递给setTimeout 改用bind绑定生成一个新函数,该函数使用不同的上下文(和默认变量)调用原始函数 你没有call将立即调用该函数,以便将其返回值传递给setTimeout 改用bind绑定生成一个新函数,该函

我正在用javascript制作一个简单的游戏。以下是我的球员方法(问题部分是在球员落水半秒后调用重置方法):

..这两者都不正确(重置正确但立即执行):


那么如何将
设置为
player
,并使用
setTimeout
将其传递给
reset

你没有
call
将立即调用该函数,以便将其返回值传递给
setTimeout

改用
bind
<代码>绑定
生成一个新函数,该函数使用不同的上下文(和默认变量)调用原始函数


你没有
call
将立即调用该函数,以便将其返回值传递给
setTimeout

改用
bind
<代码>绑定生成一个新函数,该函数使用不同的上下文(和默认变量)调用原始函数

您可以使用绑定:

您可以使用绑定:

Player.prototype = {
    update : function(){
        // player control and edge of screen detection
        // TODO factor out hardcoding into sprite width constants
        if (this.keyPressed === 'right' && this.x < 400){
            this.x += 100;
        }
        if (this.keyPressed === 'left' && this.x > 10){
            this.x += -100;
        }
        if (this.keyPressed === 'up' && this.y > 10){
            this.y -= 83;
        }
        if (this.keyPressed === 'down' && this.y < 400){
            this.y -= -83;
        }
        // reset key press
        this.keyPressed = null;

        // if reaches water, reset position
        if (this.y < 60) {
            setTimeout(this.reset, 500);
        }
    },
    reset : function(){
        // TODO factor these constants out
        // console.logs for testing
        console.log("a");
        console.log(this);
        this.x = 200;
        this.y = 405;
        console.log(this.x);
    },
    render : function(){
        ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
    },
    handleInput : function(e){
        this.keyPressed = e;
    }
}
setTimeout(this.reset.call, 500, this);
setTimeout(this.reset.call(this), 500);
setTimeout(this.reset.bind(this), 500);
setTimeout(this.reset.bind(this), 500);