requestAnimation frame error

Pet*_*tai 2 javascript html5 animation requestanimationframe

以下是导致错误(FF,Chrome和?):

JSFiddle娱乐

Engine.prototype.requestAnimationFrame = window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(/* function */ callback, /* DOMElement */ element){
            window.setTimeout(callback, 1000 / 60);
};
Run Code Online (Sandbox Code Playgroud)

完整的背景是:

var Engine = function(model) {

        this.model = model;
    };

    Engine.prototype.start = function() {
        console.log("ready")
        this.requestAnimationFrame(function() {
            console.log("done");
        });
    };

    Engine.prototype.updateUi = function() {

        console.log("update ui");
        this.requestAnimationFrame(this.updateUi);
    };

    Engine.prototype.logRAF = function() {
        console.log(window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame);
        return this;
    };

    Engine.prototype.requestAnimationFrame = window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / 60);
            };

var engine = new Engine();
engine.logRAF().start();
Run Code Online (Sandbox Code Playgroud)

FF-mozRequestAnimationFrame()中的错误如下: NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object

Chrome中的错误如下 - webkitRequestAnimationFrame(): Uncaught TypeError: Illegal invocation

在线上:

this.requestAnimationFrame...
Run Code Online (Sandbox Code Playgroud)

日志读取打印出"就绪",但不是"完成"

如果我只使用函数而不是本机RAF方法,它可以工作(记录"完成"):

JSFiddle娱乐

RequestAnimationFrames发生了什么?

Eng*_*eer 6

当你调用window函数时,context(this)必须是window,而不是你的对象(Engine的实例).bind将帮助您解决该问题:

Engine.prototype.requestAnimationFrame = 
        (window.requestAnimationFrame && window.requestAnimationFrame.bind(window)) ||
        (window.webkitRequestAnimationFrame && window.webkitRequestAnimationFrame.bind(window)) ||
        //etc...
Run Code Online (Sandbox Code Playgroud)

现场演示