Is this an immediately invoked function expression?

前端 未结 3 1040
广开言路
广开言路 2021-01-28 02:14

I\'m a javascript newbie trying to wrap my mind around this code. I got it here http://brackets.clementng.me/post/24150213014/example-of-a-javascript-closure-settimeout-inside

3条回答
  •  北海茫月
    2021-01-28 02:55

    That is, indeed, an IIFE. The syntax you quote is an IIFE of 0 arguments; the syntax you asked about is an IIFE of 1 arguments. It will assign i to x in the inner code. Compare:

    var print0 = function() {
      console.log("Hello!");
    };
    print0();
    

    is (in isolation) equivalent to

    (function() {
      console.log("Hello!");
    })();
    

    Thus the name: you create a function, then immediately invoke it.

    However, if you want an argument, nothing really changes:

    var print1 = function(name) {
      console.log("Hello, " + name);
    };
    print1("George");
    

    is (in isolation) equivalent to

    (function(name) {
      console.log("Hello, " + name);
    })("George");
    

    The parentheses here ensure that the function definition will be taken as an expression rather than as a statement. There are other ways to ensure that, a common one being

    !function() {
      console.log("Hello!");
    }();
    

    (But there are reasons to prefer the parentheses.) Since you are using it as an argument to the setTimeout call, it can't possibly be a statement, so these hacks are not necessary. It is still called "immediately invoked function expression", since you are still constructing a function expression and immediately invoking it.

    The reason why an IIFE is used here is to "capture" the value of the variable i, rather than the location of x. Without the closure trick, you would get 10 timeouts, all outputting 10 (the value of the location denoted by x when the console.log resolves).

提交回复
热议问题