在声明它时调用Javascript匿名函数不起作用,稍后调用它

Pet*_*uza 1 html javascript html5 canvas requestanimationframe

[answered]

我正在测试我的浏览器的fps为html5游戏.
我有这个代码:

var requestAnimationFrame = ( function() {
    return window.requestAnimationFrame || //Chromium 
    window.webkitRequestAnimationFrame || //Webkit
    window.mozRequestAnimationFrame || //Mozilla Geko
    window.oRequestAnimationFrame || //Opera Presto
    window.msRequestAnimationFrame || //IE Trident?
    function(callback) { //Fallback function
        window.setTimeout(callback, 1000/60);
    }
})();

var hits = 0;
var last = new Date().getTime();

var step = (function(){
    now = new Date().getTime();
    hits += 1;
    if( now - last >= 1000 ){
        last += 1000;
        console.log( "fps: "+ hits );
        hits = 0;
    }
    requestAnimationFrame( step );
})();
Run Code Online (Sandbox Code Playgroud)

它在Chrome上出现以下错误:
Uncaught Error: TYPE_MISMATCH_ERR: DOM Exception 17
第27行:requestAnimationFrame( step );

W3说这个错误是:If the type of an object is incompatible with the expected type of the parameter associated to the object.
但我实际上并没有与DOM进行交互,除了window

但是,如果我删除分配给的匿名函数的调用括号,step而只是声明该函数,并在新行上放置:
step();

有用.
为什么是这样?
两者不应该一样吗?

Fel*_*ing 9

requestAnimationFrame期望一个函数,但在你的代码中,step它不是一个函数,这是undefined因为你没有从自调函数中返回任何值.

var step = (function(){
    // this code is executed immediately, 
    // the return value is assigned to `step` 
})();
Run Code Online (Sandbox Code Playgroud)

如果删除调用括号,那么step确实是一个函数.

请参阅@ Martin对此答案的评论.我指的stepundefined 执行函数之后的事实,但当然也是undefined在第一次调用函数时.