javascript - 为什么我的 setInterval 函数只被调用一次?

标签 javascript oop data-structures event-handling dom-events

我有一个对象/函数,开头是这样的

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/

相关文章:

data-structures - 如何使用经典的自定义数据结构作为 Java 8 流

javascript - tip calc equation 在第一个输出上工作,但在第二个输出上使用 number() 返回 NaN

JavaScript 处理设备触摸屏被按住

javascript - 单击按钮显示 div,然后删除按钮

R:何时使用 setGeneric 或在命名空间中导出 s4 方法

java - Java中是否有类似于TreeSet但允许重复的数据结构?

java - 链接数据和 ComboBox 项目的最佳方式

javascript - 将循环结果插入数组

python - Django 模型中的 ModelFields 是如何分配的?

java - 绕过 setter 更改对象的值是一种不好的做法吗?