我有一个对象/函数,开头是这样的
function Game ( board, numBlocks ) {
// ...
this.speedMap = { "fast": 100, "medium": 300, "slow": 600 };
this.curSpeed;
this.mover; // the setInterval(...) function that causes the snake's movement
// This is set when a game is instantiated with startNew(...)
// ...
this.Snake = function ( game )
{
this.createNew = function ( )
{
// ...
}
this.move = function ( )
{
console.log("The move() function got called!"); // test
}
}
// ...
this.startNew = function ( spd ) {
// ...
this.snake = new this.Snake(this);
this.snake.createNew();
// ...
this.curSpeed = spd;
this.mover = setInterval(this.snake.move(), this.speedMap[this.curSpeed]);
}
(为了简单起见,我注释掉了所有与我的问题无关的代码)
由于某种原因,我附加到 setInterval
的函数仅在我实例化游戏时被调用一次
SG = new Game(snakeBoard, 16);
SG.startNew("medium");
应该每 300
毫秒调用一次。
实例: http://playclassicsnake.com/play
完整的 JavaScript: https://github.com/jamkin/Snake/blob/master/SnakeGame/Scripts/game.js
看看上面例子中的JS控制台就知道了
The move() function got called!
仅打印一次。
我在这里缺少什么?
额外问题:
在面向对象的 Javascript 中创建静态对象/函数相当于什么?具体来说,
this.speedMap = { "fast": 100, "medium": 300, "slow": 600 };
在我的对象中,对于实例化的每个此类对象都是相同的,因此它应该是 const static
或任何 JS 等效项。
最佳答案
替换:
this.snake.move()
与:
this.snake.move
所以,你将拥有:
this.mover = setInterval(this.snake.move, this.speedMap[this.curSpeed]);
setInterval
的第一个参数是一个函数。你不应该调用它。
您的代码正在执行的操作是将响应从 this.snake.move()
传递到 setInterval
关于javascript - 为什么我的 setInterval 函数只被调用一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31656133/