Why use (function(){})() or !function(){}()?

限于喜欢 提交于 2019-12-06 06:44:01

问题


I was reading In JavaScript, what is the advantage of !function(){}() over (function () {})()? then it hit me, why use :

(function(){})() or !function(){}() instead of just function(){}()?

Is there any specific reason?


回答1:


It depends on where you write this. function(){}() by itself will generate a syntax error as it is evaluated as function declaration and those need names.

By using parenthesis or the not operator, you enforce it to be interpreted as function expression, which don't need names.

In case where it would be treated as expression anyway, you can omit the parenthesis or the operator.




回答2:


I guess you are asking why use:

var fn = (function(){}());

versus:

var fn = function(){}();

The simple answer for me is that often the function on the RHS is long and it's not until I get to the bottom and see the closing () that I realise I've been reading a function expression and not a function assignment.

A full explanation is in Peter Michaux's An Important Pair of Parens.




回答3:


A slight variation on RobG's answer.

Many scripts encompass the entire program in one function to ensure proper scoping. This function is then immediately run using the double parentheses at the end. However, this is slightly different then programs which define a function that can be used in the page but not run initially.

The only difference between these two scenarios is the last two characters (the addition of the double parentheses). Since these could be very long programs, the initial parenthesis is there to indicate that "this will be run immediately."

Is it necessary for the program to run? No. Is it helpful for someone looking at the code and trying to understand it? Yes.



来源:https://stackoverflow.com/questions/7595712/why-use-function-or-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!