Javascript这个在this.method里面

时间:2014-03-09 00:54:25

标签: javascript constructor

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控制台说这个.animationObjects是未定义的,但我把它设置为一个空数组。这是为什么?

1 个答案:

答案 0 :(得分:3)

当您将其作为超时处理程序传递时,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”函数最初创建为该对象的属性值的事实确实无关紧要。重要的是该函数是如何被称为。