首页 > 解决方案 > 有没有办法让这段代码知道 g 已定义?

问题描述

请帮忙,我不知道为什么这会引发错误。我已经尝试了我能想到的一切,为什么 this.runLoop() 被定义而突然 this.processInput() 没有,我试图更好地理解类,我终于认为我明白了,我猜不是

    
class Game {
    constructor(teamSize){
        this.cpu1 = new Array(teamSize-1);
        this.cpu2  = new Array(teamSize);
        this.run = -1;
        this.init();  
    }

    init(){
    }


    shutdown(){};

    processInput = function(elapsed) {
      console.log(elapsed);
    }
    updateGame(elapsed){}
    generateOutput(elapsed){
    }

    runLoop(timestamp){
        let last;
        if(last === undefined){
            last = timestamp;
        }
        let elapsed = timestamp - last;

        this.processInput(elapsed);
        this.updateGame(elapsed);
        this.generateOutput(elapsed);
        
        last = timestamp;
        if(this.run == 1){
        window.requestAnimationFrame(this.runLoop);
        }
    };

  start(){
        this.run *= -1;
        if(this.run == 1){
        window.requestAnimationFrame(this.runLoop);
        }
    }
   
};

var g = new Game(5);
g.start();

错误是否与 window.requestAnimationFrame() 有关系,它会成为“this”所指的对象吗?

标签: javascriptclassecmascript-6

解决方案


推荐阅读