Javascript类变量未定义错误

时间:2017-09-07 06:10:33

标签: javascript canvas

所以我试图用javascipt制作一个“游戏”witc有一个矩形围绕画布,他们有定时器。当矩形计时器超过某个限制时,矩形会获得一个新的方向。

我正在尝试用类来制作矩形,这样我就可以同时运行多个矩形。但问题是我无法让类内部的函数传递给彼此(我认为这就是问题......)。

在绘制函数this.cubeLocX is not defined和this.ctx.fillStyle =“#2a2b2d”;得到错误Cannot set property 'fillStyle' of undefined

class cubeV3 {
    constructor(canvas) {
        //var canvas = document.getElementById('canvas');
        this.canvas = canvas;
        this.cubeLocX = 100;
        this.cubeLocY = 0;
        this.speed = getRandomNumber();
        this.dir = 0;
        this.turnTimer = 0;
        this.turnTimerMax = getRandomNumberV2(30,100);
        this.ctx = this.canvas.getContext("2d");
    }

    testClass() {
        alert('This is CubeV3 classes testfunction reporting in!');
        /*you have put the call to the private method inside the constructor of the javascript class. in that point the functions are not yet initialized
        but if you initialize the object like so:
        var test = new MyObject(); 
        and then do this:
        test.myMethod();
        it will work.*/
    }

    update() {
        this.turnTimer ++;
        if (this.turnTimer > this.turnTimerMax) {

            this.dir = this.turnTimerMax = getRandomNumberV2(1,4);
            this.turnTimer = 0;
            this.turnTimerMax = getRandomNumberV2(30,100);
        }

        if (this.dir == 1) {this.cubeLocY -=this.speed;}//UP
        if (this.dir == 2) {this.cubeLocY +=this.speed;}//DOWN
        if (this.dir == 3) {this.cubeLocX -=this.speed;}//LEFT
        if (this.dir == 4) {this.cubeLocX +=this.speed;}//RIGHT
    }

    draw(self,) {
        //this.cubeLocX = 555;
        resetCanvas();
        console.log(this.cubeLocX);
        alert(this.cubeLocX);
        this.ctx.fillStyle="#2a2b2d";
        this.ctx.fillRect(this.cube_loc_x,this.cube_loc_y,25,25);     
    }

} 

那我怎样才能让我的班级上班?

  

编辑调用该课程   这是在绘制之后放置的,用于调用和更新类

//setInterval(resetCanvas,10)

var testCube = new cubeV3(canvas); 
setInterval(cube, 10);
//setInterval(testCube, 10);
setInterval(testCube.update, 10);
setInterval(testCube.draw, 10);

1 个答案:

答案 0 :(得分:1)

建议1:"这"在js中可能会很棘手,如果可能的话,请避免使用它。

建议2:也许在矩形类中定义绘制函数不是最好的Oop设计。定义一个具有形状参数的独立绘图函数应该更好:

function draw(shape){
  shape.ctx.fillStyle = ...
  ...
}

通过这种方式,您可以在将来避免一些头痛。