Explain the encapsulated anonymous function syntax

后端 未结 10 1442
时光说笑
时光说笑 2020-11-21 07:02

Summary

Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})(); but

10条回答
  •  滥情空心
    2020-11-21 07:27

    In javascript, this is called Immediately-Invoked Function Expression (IIFE) .

    In order to make it a function expression you've to:

    1. enclose it using ()

    2. place a void operator before it

    3. assign it to a variable.

    Otherwise it will be treated as function definition and then you won't be able to call/invoke it at the same time by the following way:

     function (arg1) { console.log(arg1) }(); 
    

    The above will give you error. Because you can only invoke a function expression immediately.

    This can be achieved couple of ways: Way 1:

    (function(arg1, arg2){
    //some code
    })(var1, var2);
    

    Way 2:

    (function(arg1, arg2){
    //some code
    }(var1, var2));
    

    Way 3:

    void function(arg1, arg2){
    //some code
    }(var1, var2);
    

    way 4:

      var ll = function (arg1, arg2) {
          console.log(arg1, arg2);
      }(var1, var2);
    

    All above will immediately invoke the function expression.

提交回复
热议问题