requestAnimationFrame with this keyword

后端 未结 7 845
感动是毒
感动是毒 2020-11-27 15:40

I\'m using webkitRequestAnimationFrame but I\'m having trouble using it inside of an object. If I pass the this keyword it will use window

7条回答
  •  没有蜡笔的小新
    2020-11-27 16:26

    I can't guarantee that this is a good idea and that I'm right, but running .bind on every requestAnimationFrame means creating a new function on every iteration. It just doesn't sound right to me.

    That's why in my project I cached the bound function to avoid the anti-pattern.

    Simple example:

    var Game = function () {
        this.counter = 0;
        this.loop = function () {
            console.log(this.counter++); 
            requestAnimationFrame(this.loop);
        }.bind(this);
        this.loop();
    }
    var gameOne = new Game();
    

    If you have a more complex project with prototype inheritance you can still create a cached function with "this" bound in object's constructor

    var Game = function () {
        this.counter = 0;
        this.loopBound = this.loop.bind(this);
        this.loopBound();
    }
    Game.prototype.loop = function () {
        console.log(this.counter++); 
        requestAnimationFrame(this.loopBound);
    }
    var gameOne = new Game();
    

    Thoughts? http://jsfiddle.net/3t9pboe8/ (look in the console)

提交回复
热议问题