var AnimationManager = function (time, completionMethod) {
    "use strict";
    this.animationObjects = [];
    this.time = time;
    this.add = function (animationObject) {
        this.animationObjects.push(animationObject);
    };
    this.completionMethod = completionMethod;
    this.currentStage = 0;
    this.maximumStage = this.time * FPS;

    this.tick = function () {
        this.currentStage += 1;
        var i;
        for (i = 0; i < this.animationObjects.length; i += 1) {
            this.animationObjects[i].applyAnimation(this.currentStage);
        }

        if (this.currentStage < this.maximumStage) {
            console.log(this.currentStage);
            setTimeout(this.tick, 1000.0 / FPS);
        } else {
            this.completionMethod();
        }
    };

    //Call this to start
    this.startAnimation = function () {
        this.timer = setTimeout(this.tick, 1000.0 / FPS);
    };
};


chrome控制台说this.animationObjects是未定义的,但我将其设置为空数组。为什么是这样?

最佳答案

当您将this.tick的上下文作为超时处理程序传递时,它会丢失。采用:

 this.timer = setTimeout(this.tick.bind(this), 1000.0 / FPS);


或稍稍过时的:

 var mgr = this;
 this.timer = setTimeout(function() { mgr.tick(); }, 1000.0 / FPS);


this的值在每次调用函数时确定。函数和任何特定对象之间没有固有的长期关系。换句话说,“ tick”函数最初是作为该对象的属性值创建的,这一事实并不重要。重要的是该函数的调用方式。

关于javascript - 这个this.method中的Javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22277098/

10-11 22:40
查看更多