http://stackoverflow.com/questions/6065169/requestanimationframe-with-this-keyword

Observe that you call obj.draw as :

<button onclick="obj.draw()

The first time obj.draw is called, the context is different than when it called by requestAnimationFramemultiple times, as a callback function before the repaint.

So try by saving this in a variable which is outside the scope of the callback function.

Something like :

var obj = {    
    //...

    draw: function () {
        var sender = this;
        var draw = function () {
            document.getElementById(sender.id).style.left = (sender.speed++) + 'px';
            window.requestAnimationFrame(draw);
        }
        draw();
    }
}

Here is an updated demo of how this would look like.

http://stackoverflow.com/questions/6065169/requestanimationframe-with-this-keyword

原文地址:https://www.cnblogs.com/goldenstones/p/4863764.html