what is the lexical environment of a function argument?

前端 未结 3 1093
深忆病人
深忆病人 2021-01-27 23:06

Javascript supports First Class Functions, in which case we can pass the function as an argument. An anonymous function that is defined inside an argument list of another functi

3条回答
  •  情书的邮戳
    2021-01-27 23:59

    Calling an IIFE is effectively the same as first assigning the function to a variable, then then calling the function through that variable; as with any other use of anonymous functions, it's just a shortcut that avoids giving a name to the function. So:

    (function(p1,p2){
       p2(p1);
    })(true, function(p1){  // an anonymous function passed as an argument.
       m = 3;
       if(p1){...}
    });
    

    is equivalent to:

    var temp = function(p1,p2){
       p2(p1);
    };
    temp(true, function(p1) {
       m = 3;
       if(p1){...}
    });
    

    except for the addition of temp to the outer scope; since this variable doesn't appear anywhere else, it has no effect. The scopes of all other variables are identical in the two scenarios.

提交回复
热议问题