【问题标题】:Why does my code in setTimeout not work in JavaScript?为什么我在 setTimeout 中的代码在 JavaScript 中不起作用?
【发布时间】:2015-01-01 22:21:36
【问题描述】:

我的方法,Chomp.prototype.animate 不能正常工作。当函数不适用Chomp.prototype.playerMove 时,我的代码有效。

Chomp.prototype.playerMove被应用时,那么addEventListener之前涉及counter的if语句有时可以执行addEventListener,即使counter大于1,那次它会多次执行addEventListener中的函数,具体取决于代码在执行之前运行了多长时间。那些时候,它不应该执行 addEventListener,如果它执行了,那么 counter 应该被添加到多个,然后不再执行。计数器被添加到多个,即使在 addEventListener 被多次执行的这些时间。

更奇怪的是,当我有 Chomp.prototype.animate 总是将 counter 设置为 1 而不是 0 时,它仍然会执行一次显示 if (counter < 1) 的 if 语句。此外,当应用Chomp.prototype.playerMove 时,Chomp.prototype.chomping 不能正常工作。 (它在没有Chomp.prototype.playerMove 的情况下也可以工作)。这很奇怪,我不明白这个问题。

如果有人要求我的代码的某个部分,那么我可以发布它,但我的完整代码可能并非对这个问题都有用。

var counter = 0;
var rotation;
var Chomp = function(x, y) {
  /*many properties*/
}
Chomp.prototype.chomping = function() {
  /*properties and conditions, etc.*/
}
Chomp.prototype.animate = function() {
  var that = this;
  Chomp.prototype.chomping.apply(this);
  Chomp.prototype.playerMove.apply(this);
  //counter = 1;
  counter = 0;
  setTimeout(function(){
    Chomp.prototype.animate.apply(that);
  }, 100);
}
Chomp.prototype.playerMove = function() {
  var that = this;
  /*values*/
  var yNew = 0, xNew = 0, rotate = "";
  var once = function(event) {
    /*conditions for keys, etc.*/
    Chomp.prototype.move.call(that, xNew, yNew, rotate);
    /*values*/
    removeEventListener("keydown", once);
  }
  if (counter < 1)
    addEventListener("keydown", once); 
  /*more code*/
  }
Chomp.prototype.move = function(xNew, yNew, rotate) {
  var that = this;
  counter += 1;
  /*loops, conditions, etc.*/
var yellow = new Chomp(30, 60);
Chomp.prototype.animate.apply(yellow);

提前致谢! :)

【问题讨论】:

  • 我在eloquentjavascript.net/code 中运行我的代码,如果有影响的话,但可能不会。
  • 你为什么打电话给Chomp.prototype.animate.apply(yellow)而不是yellow.animate()?与Chomp.prototype.chomping.apply(this)相同的应该是this.chomping()
  • @RobG,我需要yellowChomp.prototype.animate 的这个,也许它们都可以工作?当我没有应用Chomp.prototype.playerMove 时,它确实有效,因此它一定不是问题。
  • @RobG,两者确实有相同的效果,所以这不是问题,我已经测试过了。不过,感谢您的建议。
  • 继承应该是这样工作的。函数的 this 由调用设置,因此当您执行 yellow.animate() 时,animate 中的 this 将变为 yellow (直到 ES6 箭头函数出现一种隐式 bind...)。

标签: javascript event-handling call


【解决方案1】:

在调用 Chomp.prototype.animate 时,您正在应用 yellow 上下文。 yellowChomp 的一个实例,当您在Chomp.prototype.animate 声明中时,将绑定到this,这意味着您对this 的所有绑定现在都绑定到Chomp 实例@ 987654328@,而不是 Chomp.prototype 对象。如果您打算将它们与Chomp 的实例而不是Chomp.prototype 一起使用(它们是两个不同的对象!),我不确定为什么要使用Chomp.prototype 来调用原型方法中的所有方法。在所有Chomp.prototype 方法中使用this 可能更有意义。

有必要查看其余代码,因为您的原型在您刚刚展示的其他方法中创建了大量副作用/* etc... */,我不确定这些副作用触发了什么逻辑在您的程序中...发布更多代码或 PM 我,我们可以一起进行重构,以避免这些问题。干杯

附言想发表评论,但太长了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2021-03-17
    • 2018-04-24
    • 2019-01-07
    • 2014-04-28
    • 2017-06-18
    • 2019-03-12
    相关资源
    最近更新 更多