为什么requestAnimFrame需要绑定(this)

时间:2015-03-02 09:24:02

标签: javascript prototype bind requestanimationframe

为什么window.requestAnimFrame必须像这样调用:window.requestAnimFrame(this.__proto__.animate.bind(this));而不是window.requestAnimFrame(this.__proto__.animate);

我的js-class看起来像:

Game = function (moduleConfig, gameConfig) {
    this.moduleConfig = moduleConfig;
    this.gameConfig = gameConfig;

    // Game-Commands
    this.keyCommands = {
        moveLeft: false,
        moveRight: false
    };

    // Some init stuff

    requestAnimFrame(this.animate.bind(this));


    return this;
}

/**
 * Init the game system
 * @param {moduleConfig} moduleCongif - Module-Config instance
 */
Game.prototype = {

    // General member
    self: null,
    moduleConfig: null,
    gameConfig: null,

    // Game member
    renderer: null,
    catcher: null,
    stage: null,

    // Nested 'static' objects
    keyCommands: {
        moveLeft: false,
        moveRight: false
    },


    // Some more stuff

    /**
     * Main loop
     */
    animate: function () {
        window.requestAnimFrame(this.__proto__.animate.bind(this));

        // Some more things to do
    }
}

如果我不使用bind,我会收到以下错误消息:Failed to execute 'requestAnimationFrame' on 'Window': The callback provided as parameter 1 is not a function.

谢谢!

2 个答案:

答案 0 :(得分:1)

因为你的动画是Game的方法,因为它是一个递归函数,所以需要一个上下文才能调用下一个动画。

现在我已经告诉过你了(或者也许是某人),但是.bind因为很多原因而使用起来非常糟糕 - 因为你的主要原因是它非常慢并且你正在制作一个需要运行的渲染功能非常快

为了避免使用bind我会这样做:

animate: function () {
    var self = this
    window.requestAnimFrame(function(){
        self.animate();
    });

    // Some more things to do
}

答案 1 :(得分:1)

window.requestAnimFrame可以调用window.requestAnimationFrame,它将每秒调用参数函数。没有' bind(this)',' this。 proto 。动画'将调用window。 proto .animate.With' bind(this)',它将调用Game的动画功能,这将是正确的。'绑定(本)'只需将游戏背景传递给此。