【发布时间】: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,我需要
yellow是Chomp.prototype.animate的这个,也许它们都可以工作?当我没有应用Chomp.prototype.playerMove时,它确实有效,因此它一定不是问题。 -
@RobG,两者确实有相同的效果,所以这不是问题,我已经测试过了。不过,感谢您的建议。
-
继承应该是这样工作的。函数的 this 由调用设置,因此当您执行
yellow.animate()时,animate 中的 this 将变为 yellow (直到 ES6 箭头函数出现一种隐式 bind...)。
标签: javascript event-handling call