0

您好,我使用对象构造函数来管理一些动画,在某些情况下,我想在动画完成时传递一个回调以使其他一些元素出现。问题是如果在 if 语句中我记录了一种回调类型,它是一个有效的函数,但是当我在 if 语句中执行日志时,如果总是未定义,我很感激有人可以帮助我,我也离开了代码,所以你们可以检查出来。

// CONSTRUCTOR WHO MANAGE THE ANIMATIONS FOR THE WEBSITE

function SpriteAnimation(frameWidth, spriteWidth, spriteElement, shouldLoop, frameRate){
    this.frameWidth = frameWidth;
    this.spriteWidth = spriteWidth;
    this.selector = document.getElementById(spriteElement);
    this.shouldLoop = shouldLoop ;
    this.curPx = 0;
    this.frameRate = frameRate;
}

SpriteAnimation.prototype.start = function(callback){
    this.selector.style.backgroundPosition = "-" + this.curPx + "px 0px";
    this.curPx += this.frameWidth;

    if (this.curPx < (this.spriteWidth - this.frameWidth)){
        setTimeout(this.start.bind(this), this.frameRate);
    }else if (this.curPx > (this.spriteWidth - this.frameWidth)){
        console.log(typeof callback);
    }else if(this.shouldLoop){
        this.curPx = 0;
        this.start();
    }
};

稍后在我实例化它并运行开始的代码中:

var letter = new SpriteAnimation(790, 18163, "letter", false, 53.3);

letter.start(function(){
    console.log("hola");
});
4

2 回答 2

2

You did not pass the callback in your setTimeout, I would suggest doing this:

    setTimeout(function(){
        this.start(callback);
    }, this.frameRate);
于 2013-11-01T16:51:44.637 回答
1

一种可能性是 setTimeout 调用了 start 函数

SpriteAnimation.prototype.start = function(callback){
    this.selector.style.backgroundPosition = "-" + this.curPx + "px 0px";
    this.curPx += this.frameWidth;

    if (this.curPx < (this.spriteWidth - this.frameWidth)){
        setTimeout((function(){
            this.start(callback)
        }).bind(this), this.frameRate);
    }else if (this.curPx > (this.spriteWidth - this.frameWidth)){
        console.log(typeof callback);
    }else if(this.shouldLoop){
        this.curPx = 0;
        this.start();
    }
};
于 2013-11-01T16:53:48.943 回答