尽管被赋值

时间:2015-12-09 20:20:54

标签: javascript html5-canvas

所以我正在构建一个小游戏,其中一个角色就是这个Golem对象:

function Golem(){
    var self = this;
    this.width = 470;
    this.height = 360;
    this.drawX = canvasEntities.width/3;
    this.speed = 30;
    this.isLeftKey = false;
    this.isRightKey = false;
    this.isSpacebar = false;
    this.spritesheet = spritesheetgolemleft;
    this.animate = function(){
        requestAnimFrame(self.animate);
        //this console log returns undefined
        console.log(self.spritesheet)
        this.spritesheet.update();
        self.spritesheet.draw(self.drawX,canvasEntities.height/3);
    }
}

spritesheetgolemleft变量已在最顶层(全局)定义:

var spritesheetgolemleft = new SpriteSheet('images/golem_walkleft.png',470,360,3,6);

这是SpriteSheet类:

function SpriteSheet(path, frameWidth, frameHeight, frameSpeed, endFrame){
    var image = new Image();
    var framesPerRow,
            currentFrame = 0,
            counter = 0;
    //# of frames after image loads
    var self = this;
    image.onload = function(){
        framesPerRow = Math.floor(image.width/frameWidth);
    };
    image.src = path;
    this.update = function(){
        if(counter == (frameSpeed - 1))
            currentFrame = (currentFrame + 1) % endFrame;
        counter = (counter + 1) % frameSpeed;
    }
    this.draw = function(x,y){
        var row = Math.floor(currentFrame / framesPerRow);
        var col = Math.floor(currentFrame % framesPerRow);
        //draw image into the Entities canvas
        ctxEntities.drawImage(
            image,
            col * frameWidth, row*frameHeight,
            frameWidth, frameHeight,
            x,y,
            frameWidth, frameHeight);
    };
};

我得到的错误发生在Golem()对象的倒数第二行:

this.spritesheet.update();

它给了我一个TypeError,无法读取未定义的属性'update'。认为这是范围的某种问题,我在顶部添加了self = this hack,但它仍然不起作用。我究竟做错了什么?提前致谢。

1 个答案:

答案 0 :(得分:0)

事实证明我在创建spritesheets之前实例化了一个对象。我的错误:/