0

这是来自 https://github.com/Khan/khan-exercises/blob/master/khan-exercise.js的代码

for ( var i = 0; i < loading; i++ ) (function( mod ) {
    if ( !testMode && mod.src.indexOf("/khan-exercises/") === 0 && mod.src.indexOf("/MathJax/") === -1 ) {
        // Don't bother loading khan-exercises content in production
        // mode, this content is already packaged up and available
        // (*unless* it's MathJax, which is silly still needs to be loaded)
        loaded++;
        return;
    }

    // Adapted from jQuery getScript (ajax/script.js)
    var script = document.createElement("script");
    script.async = "async";

    for ( var prop in mod ) {
        script[ prop ] = mod[ prop ];
    }

    script.onerror = function() {
        // No error in IE, but this is mostly for debugging during development so it's probably okay
        // http://stackoverflow.com/questions/2027849/how-to-trigger-script-onerror-in-internet-explorer
        Khan.error( "Error loading script " + script.src );
    };

    script.onload = script.onreadystatechange = function() {
        if ( !script.readyState || ( /loaded|complete/ ).test( script.readyState ) ) {
            // Handle memory leak in IE
            script.onload = script.onreadystatechange = null;

            // Remove the script
            if ( script.parentNode ) {
                script.parentNode.removeChild( script );
            }

            // Dereference the script
            script = undefined;

            runCallback();
        }
    };

    head.appendChild(script);
})( urls[i] );

奇怪的事情:我们看到的是自调用函数,而不是通常的 for 循环代码块!(在其他自调用函数内部)为什么会这样?这个函数将如何运行?

4

2 回答 2

3

基本上for loop每次都运行函数,并将值url[i]传递给mod参数。

for ( var i = 0; i < loading; i++ ) (function( mod ) {...The code...})(urls[i]);

如果你在代码中注意到你会看到这个

(function( mod ) {...The code...})(urls[i])

这是一个传入urls[i] 参数的函数调用mod

于 2011-09-23T19:49:30.617 回答
1

这是一个奇怪的结构,但基本上如果你{}从 for 循环中排除,它只会为每次迭代运行下一行,它类似于排除if 你想要一个 one- {}line 。ifif

所以它基本上相当于这个:

function doSomething(){...}

for ( var i = 0; i < loading; i++ ) {
   doSomething(urls[i]);
}

doSomething 是那个大函数在哪里。

于 2011-09-23T19:51:02.980 回答