Javascript Syntax: Immediately Invoked Function [removed]IIFE) with parameters

后端 未结 2 1882
走了就别回头了
走了就别回头了 2021-01-22 15:52

I have always seen code like this:

(function(){
   //code here
})();

How does this code work? Which function receives which parameters?

<
2条回答
  •  醉梦人生
    2021-01-22 16:19

    function($){
      //other code here
    }
    

    This block is passed as a parameter to the outer IIFE. It might be clearer to write it like this:

    var factoryDef = function($) { ... };
    
    (function(factory) {
        // this is the outer IIFE
        var someVar = {};
        // you can call:
        factory(someVar);
        // the previous line calls factoryDef with param someVar
    }(factoryDef));
    

    So factory(someVar) is the same as factoryDef({}); the latter is simply the value of factory (which is the function factoryDef) called with the value of someVar (which is {}.)

    Does that make sense?

提交回复
热议问题