Javascript这里this.method [英] Javascript this inside this.method

查看:233
本文介绍了Javascript这里this.method的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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未定义,但是我将它设置为空数组。为什么是这个?

The chrome console is saying this.animationObjects is undefined but I set it to an empty array. why is this?

推荐答案

this.tick 的上下文丢失当你将它作为超时处理程序。使用:

The context for this.tick is lost when you pass it as a timeout handler. Use:

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

或略微古老的:

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

this 调用函数。函数和任何特定对象之间没有固有的长期关系;换句话说,tick函数最初创建为该对象的属性的值真的没有关系。重要的是如何调用

The value of this is determined upon each call to a function. There's no inherent long-term relationship between a function and any particular object; in other words, the fact that the "tick" function was originally created as the value of a property of that object really doesn't matter. What matters is how the function is called.

这篇关于Javascript这里this.method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆