Explain the encapsulated anonymous function syntax

后端 未结 10 1446
时光说笑
时光说笑 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:09

    Those extra parenthesis creates extra anonymous functions between global namespace and anonymous function that contains the code. And in Javascript functions declared inside other functions can only access namespace of parent function that contains them. As there is extra object (anonymious function) between global scope and actual code scoping is not retained.

提交回复
热议问题