开发者

self invoking function in for loop

Here's code from 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
        Kha开发者_高级运维n.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] );

Strange thing: instead of usual for loop code block we see self invoking function!(inside of other self invoking function) Why is that? how will this function run?


Basically the for loop runs the function each time with value url[i] passed into the mod parameter.

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

if you notice in the code you will see this

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

which is a function call passing urls[i] in to the parameter mod


It's an odd construct, but basically if you exclude the {} from a for loop, it will simply run the next line for each iteration, it's similar to excluding {} with an if if you want a one-line if.

So it's basically equivalent to this:

function doSomething(){...}

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

Where doSomething is that large function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜