JavaScript scope and closure

前端 未结 7 1932
执笔经年
执笔经年 2020-11-28 09:21

I\'m trying to wrap my head around closures (there\'s a joke in there somewhere) and I ran across this:

(function () { /* do cool stuff */ })();
7条回答
  •  感情败类
    2020-11-28 10:16

    Putting the function declaration inside parens creates an expression which evaluates to the anonymous function within. Therefore, the first parenthetical evaluates to a function.

    The "empty parens" at the end invoke the defined function, so "//do cool stuff" executes immediately.

    This is a way to execute code on-the-fly while also keeping variables out of the global scope.

    What is illustrated here, however, has nothing to do with closures - at least not directly. Closures are about maintaining a lexical scope after a parent function has already exited.

提交回复
热议问题