Why do you need to invoke an anonymous function on the same line?

前端 未结 19 1747
走了就别回头了
走了就别回头了 2020-11-22 00:17

I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:

//          


        
19条回答
  •  滥情空心
    2020-11-22 01:01

    It is a self-executing anonymous function. The first set of brackets contain the expressions to be executed, and the second set of brackets executes those expressions.

    (function () {
        return ( 10 + 20 );
    })();
    

    Peter Michaux discusses the difference in An Important Pair of Parentheses.

    It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.

    See:

    1. Closure (computer science)
    2. JavaScript Namespacing
    3. Important Pair of Javascript Parentheses

提交回复
热议问题