2

以下导致错误(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);
};

完整的上下文是:

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();

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

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

在线上:

this.requestAnimationFrame...

日志读取打印出“准备好”,但没有“完成”

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

JSFiddle 娱乐

RequestAnimationFrames 发生了什么?

4

2 回答 2

6

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

Engine.prototype.requestAnimationFrame = 
        (window.requestAnimationFrame && window.requestAnimationFrame.bind(window)) ||
        (window.webkitRequestAnimationFrame && window.webkitRequestAnimationFrame.bind(window)) ||
        //etc...

现场演示

于 2012-12-28T11:14:14.330 回答
2

requestAnimationFrame应该在 : 的上下文中调用,如此处所述:windowChrome中的“Uncaught TypeError: Illegal invocation”this.requestAnimationFrame.call(window, ...);

于 2012-12-28T11:18:11.273 回答