为什么 requestAnimFrame 需要 bind(this)

Why requestAnimFrame need bind(this)

为什么 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.

谢谢!

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

现在我已经告诉过你(或者可能是其他人)但是 .bind 真的不好用,原因有很多——对你来说,主要原因是它非常慢,而且你正在制作一个需要的渲染功能运行 极快

为了避免使用绑定,我会这样做:

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

    // Some more things to do
}

window.requestAnimFrame可能会调用window.requestAnimationFrame,它会在每个second.Without调用参数函数'bind(this)','this.proto.animate'会调用window。proto.animate.With 'bind(this)',它将调用游戏的动画函数,这将是正确的。'bind(this)' 只需将游戏上下文传递给它即可。