Javascript类变量和类方法不能在类内引用

时间:2018-03-13 18:30:00

标签: javascript class constructor

这个问题一直困扰着我。我确信这个问题已得到解答,但我一直在寻找大约半小时的时间。

这是我的问题:

在Javascript中,我创建了一个名为Game的类。

该课程目前看起来像这样:

class Game {
    this.test = "";
    this.number = 0;
    constructor()
    {
        this.cWidth = 480;
        this.cHeight = 360;
        this.i = 0;

    }
    run()
    {

        var human = new User(192,175);
        var bot1 = new Bot(339,92);
        var bot2 = new Bot(352,255);
        setInterval(this.updateGameArea, 1000 / 60);
    }
    updateGameArea()
    {
        this.clear();
        this.update();

    }
    clear()
    {
        ctx.clearRect(0,0,this.cWidth,this.cHeight);
        ctx.fillStyle = "#FFFFFF"
        console.log("cleared! cwidth=" + this.cWidth + "; cHeight = " + this.cHeight);
    }
    update()
    {
        var pos = getCoords();
        drawMousePos();
        return;
    }
}

Game game = new game();
game.run();

请注意,该类也在Jquery的$(document).ready(function(){})中运行,但是应该可以工作,因为其他更简单的类可以工作。

我遇到了多个问题:

  1. 无法在课外定义变量。 testnumber抛出语法错误,说game.js:161 Uncaught SyntaxError: Unexpected token .
  2. 根据Mozilla class syntax page,似乎允许一个人使用this关键字实例化变量而不使用构造函数。

    1. updateGameArea()中,无法引用clear()update()。但是,在run(),他们可以。我已经能够通过将clear()update()设置为静态并使用Game.update()Game.clear()来调用它们来解决这个问题,但我更愿意,如果我能做到这一点正确的方式。

    2. 变量cWidthcHeight不保留其值。当我在clear()静态时对其进行测试时,cWidthcHeight都未定义。

    3. 非常感谢任何帮助。

0 个答案:

没有答案