Javascript 如何设置setInteval以使其应用于特定的子类

Javascript 如何设置setInteval以使其应用于特定的子类,javascript,Javascript,我有一个叫做MovingThing的类,它被一个叫做Monster的类扩展。每个怪物都需要自己的设置间隔时间。以下是我正在使用的: GameBoard.js this.monsters = [ new Monster(this, 'monster_0'), new Monster(this, 'monster_1'), new Monster(this, 'monster_2') ] movingThings.js class M

我有一个叫做MovingThing的类,它被一个叫做Monster的类扩展。每个怪物都需要自己的设置间隔时间。以下是我正在使用的:

GameBoard.js

this.monsters = [
        new Monster(this, 'monster_0'),
        new Monster(this, 'monster_1'),
        new Monster(this, 'monster_2')
        ]
movingThings.js

class Monster extends MovingThing{
constructor(gameboard, dom_id) {
    super('monster', 20, document.getElementById(dom_id), gameboard);
}

class MovingThing {

characterType = '';
speed = 0;
dom = null;
gameBoard = null;
step = 4;
direction = 0;
gameLoop = null
size = 40;
x = 0;
y = 0;
sprite = {
    left: 0,
    right:0,
    top: 0,
    bottom: 0
};

constructor(characterType, speed, dom, gameboard) {
    this.characterType = characterType;
    this.speed = speed;
    this.dom = dom;
    this.gameBoard = gameboard;

    self = this;
    this.gameLoop = setInterval(function(){self.moveLoop()}, this.speed);
}

moveLoop(){
    if (!this.gameBoard.is_active) return;
    //if (this.characterType == 'monster') console.log(this.x, this.y)
    switch (this.direction) {
        case 37:
            this.sprite.left -= 2;
            break;
        case 40:
            this.sprite.top += 2;
            break;
        case 39:
            this.sprite.left += 2;
            break;
        case 38:
            this.sprite.top -= 2;
            break;
    }

    this.drawSprite();
     if (this.sprite.left % this.size === 0  &&
          this.sprite.top % this.size === 0  ){
        this.x = this.sprite.left / this.size;
        this.y = this.sprite.top / this.size;
        this.handleIntersection();
    }
    // console.log(this.direction)
}

setPosition(grid_x, grid_y){
    this.x = grid_x;
    this.y = grid_y;
    this.sprite.top = grid_y * this.size;
    this.sprite.left = grid_x * this.size;
    this.drawSprite();
}

drawSprite(){
    this.sprite.bottom = this.sprite.top + this.size;
    this.sprite.right = this.sprite.left + this.size;

    this.dom.style.top = this.gameBoard.gameBoardPosition.top + this.sprite.top + 'px';
    this.dom.style.left = this.gameBoard.gameBoardPosition.left +  this.sprite.left + 'px';
};

}
所发生的只是最后一个怪物移动,它移动的速度是预期的3倍。就像有3个计时器在运行,但它们都移动同一个怪物


除了这段代码,我尝试将setinterval放入Monster构造函数中,但出现了相同的问题。

您的
self
是全局的,所以您一直在覆盖它。使用
let
将其范围限定到功能:

let self = this;
this.gameLoop = setInterval(function(){self.moveLoop()}, this.speed);

@谢谢。这是JavaScript设计中的一个大错误。