【问题标题】:setting timeout function within an object在对象中设置超时功能
【发布时间】:2015-10-04 23:24:56
【问题描述】:

我正在用一个英雄人物创建一个游戏,他的任务是在画布上收集水果。

问题是每个水果在画布上都有自己的过期时间。 例如,香蕉会出现 5 秒,橙色会出现 10 秒等等。

我想做的事情是创建一个对象,该对象的每个实例都有一个计时器,该计时器在选定的时间后更改布尔值

我的代码如下所示:

function apple(timeToStay,score){
this.kind = "apple";
this.timeTostay = timeToStay;
this.score=score;
this.imgsrc =  "images/apple.png";
this.x = 32 + (Math.random() * (canvas.width - 64));
this.y = 32 + (Math.random() * (canvas.height - 64));
this.removeMe = false;

setTimeout(function() { this.removeMe=true; }, timeToStay*1000);

return this;

}

如您所见,我认为使用实例设置超时将在 5 秒后触发,例如,如果我创建了它 var obj = apple(5,5)

一开始 obj.removeMe 应该是假的,但 5 秒后它应该变成真。

【问题讨论】:

  • this 是函数作用域。所以它在超时函数内部发生了变化。在构造函数中使用var _this = this,在超时时使用_this

标签: javascript oop


【解决方案1】:

发生这种情况是因为您作为参数传递给 setTimeout 方法的函数没有保持相同的上下文,因为 Javascript's lexical scoping

您可以使用Function.prototype.bind 覆盖该行为,例如:

setTimeout(function() { this.removeMe=true; }.bind(this), timeToStay*1000);

【讨论】:

    【解决方案2】:

    这应该可行:

    function apple(timeToStay,score){
      this.kind = "apple";
      this.timeTostay = timeToStay;
      this.score=score;
      this.imgsrc =  "images/apple.png";
      this.x = 32 + (Math.random() * (canvas.width - 64));
      this.y = 32 + (Math.random() * (canvas.height - 64));
      this.removeMe = false;
    
      var base = this;
    
      setTimeout(function() { base.removeMe=true; }, timeToStay*1000);
    
      return this;
    }
    

    【讨论】:

    • 这是非常糟糕的做法,您应该始终使用绑定/调用/应用来解决此类问题。
    猜你喜欢
    • 1970-01-01
    • 2022-10-05
    • 2012-01-06
    • 1970-01-01
    • 2016-10-30
    • 2021-05-29
    • 1970-01-01
    • 2016-11-29
    • 2019-01-27
    相关资源
    最近更新 更多