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

Why is my setInterval function only being called once?

本文关键字:一次 调用 我的 setInterval 函数 为什么      更新时间:2023-09-26

我有一个对象/函数,它开始于

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控制台,并查看

move()函数被调用了!

只打印一次。

我在这里错过了什么?

奖金问题:

在面向对象的Javascript中创建一个静态对象/函数的等效是什么?具体地说,

this.speedMap = { "fast": 100, "medium": 300, "slow": 600 };

在我的对象是相同的每一个这样的对象被实例化,所以它应该是const static或任何JS等效的

Replace:

this.snake.move()

:

this.snake.move

所以,你有:

this.mover = setInterval(this.snake.move, this.speedMap[this.curSpeed]);

setInterval的第一个参数是一个函数。你不应该叫它。
您的代码正在做的是将响应从this.snake.move()传递到setInterval