对象的属性未定义,尽管已指定值

Attribute of an object is undefined despite being assigned value

本文关键字:属性 未定义 对象      更新时间:2023-09-26

所以我正在构建一个小游戏,其中一个角色就是这个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,但它仍然不起作用。我做错了什么?提前谢谢。

事实证明,在创建精灵表之前,我正在实例化一个对象。我的错误:/