Javascript 在功能内设置计时器

Javascript 在功能内设置计时器,javascript,function,object,timer,Javascript,Function,Object,Timer,我有一个游戏对象,我想在一段时间后重新生成(激活)。每次时间到期时,我都会出现以下错误: Uncaught TypeError: Object [object global] has no method 'SpawnCounter' 不知道我做错了什么?这是我的目标的一部分: this.Update = function(){ //Collisions if(this.active){ if(player.Intersects(this)){

我有一个游戏对象,我想在一段时间后重新生成(激活)。每次时间到期时,我都会出现以下错误:

Uncaught TypeError: Object [object global] has no method 'SpawnCounter'
不知道我做错了什么?这是我的目标的一部分:

this.Update = function(){
    //Collisions
    if(this.active){
        if(player.Intersects(this)){
            console.debug("Player Touching Pick Up!");
            if(this.type == "weapon")
                player.weapon = this.subtype;
            this.active = false;
        }
    }
    else{
        //THIS IS THE TIMER
        setTimeout( function(){ this.SpawnCounter(); }, 2000 );
    }
};

this.SpawnCounter = function(){
    this.active = true;
};

所有这一切,只是一个游戏拾取-在2秒后重新出现。

也许可以尝试将其范围限定到另一个变量

this.Update = function(){
    var that = this;
    //Collisions
    if(this.active){
        if(player.Intersects(this)){
            console.debug("Player Touching Pick Up!");
            if(this.type == "weapon")
                player.weapon = this.subtype;
            this.active = false;
        }
    } else{
        //THIS IS THE TIMER
        setTimeout( function(){ that.SpawnCounter(); }, 2000 );
    }
};

this.SpawnCounter = function(){
    this.active = true;
};

这段代码在哪里执行?执行中的
与setTimeout中的
的范围是什么(
实际上指的是窗口对象)?…但是
不是定时调用中的对象。使用变量引用对象,即do
var=this
外部。通过我的主要游戏更新函数“var Update=setInterval(function(){@Bergi-well,如果
this
在定义
SpawnCounter
时引用窗口对象,将调用“Update”(不太可能在全球范围内执行)这是JSre中非常常见的一种做法:“合法”——我相信,因为有一个引用可能会导致泄漏。可以释放该引用,或者最好在全局可访问的对象中有一个对SpawnCounter的引用,然后以这种方式调用该方法?