简体   繁体   中英

Could I have an explanation of the syntax of this javascript closure?

I recently had a question answered that has, for me, raised syntax questions. I have looked at explanations of closures on SO but the answers do not address my specific questions below. I have tried discussing this with the person who provided me with the answer and they suggested I ask another question. Here is the solution I was offered, which works, but which I do not understand:

for (var loop = 0;loop<onHoverSections.length;loop++) {
    var extractedID = onHoverSections[loop].onHover;
    for (var loopInner = 0;loopInner<sections.length;loopInner++) {
        if (sections[loopInner].ID==extractedID) {
            ( function(p_loop, p_loopInner) {
                onHoverSections[p_loop].hover(
                    function() {
                        sections[p_loopInner].trigger('onHover');
                    },
                    function() {
                        //
                    }
                );
            }
            (loop, loopInner) );
        }
    }
}

My questions relate to this section of code:

( function(p_loop, p_loopInner) {
    // .. code removed
}
(loop, loopInner) );

My questions are:
Why are the 'loop' and 'loopInner' parameters in a set of brackets AFTER the function definition?
If they are parameters of a different function, where is the function definition?
Why does this function not work when the outer brackets are removed?

I would like to understand this syntax well enough so I can replicate this code in other cases and understand WHY it works. Thanks.

It's an IIFE . Perhaps it would help you to see what's happening by moving the parenthesis:

(function(p_loop, p_loopInner) {
    // .. code removed
})(loop, loopInner);

As we can see, the first expression returns an anonymous function that takes p_loop and p_loopInner parameters. Then with (loop, loopInner); we invoke it just like any other function.

There are a few different names for them - Self executing function, Self invoking function or Immediately invoked function expression (IIFE).

Basically it is a function that is created and executed immediately.

In the code above the function is

  1. created to take two parameters, called p_loop and p_loopInner within the function.
  2. Immediately invoked and passed two parameters - loop and loopInner

The purpose of this is to preserve the values of the loop indeces, so that the correct values are accessible within the inner scope.

Explained in detail here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM