Does parenthetical notation for self-invoked functions serve a purpose in Javascript? [duplicate]

有些话、适合烂在心里 提交于 2019-12-10 01:43:11

问题


I get confused when I see examples of self invoked anonymous functions in Javascript such as this:

(function () { return val;}) ();

Is there a difference between this syntax and the following:

function() { return val;} ();

If someone can give me a concrete difference, it would help put to rest a question that's been bugging me for ages...


回答1:


Javascript doesn't have a block scope, so this is a way to create a temporary local scope that doesn't pollute the global namespace. The parentheses serve two purposes:

  1. Some implementations of javascript flip out if they're missing.
  2. It signals to readers that something different from a normal function declaration is going on. So as a convention, it signals that this function is being used as a scope.

see here: http://peter.michaux.ca/articles/an-important-pair-of-parens




回答2:


In Safari 4, the following code (without the parentheses) results in "SyntaxError: Parse error":

function() { alert("Test"); }();

...but the following code works as expected:

(function() { alert("Test"); })();

Update: I also tried the code in Firefox 3 (via Firebug), and it behaved just like Safari.




回答3:


The reason

function() { return val;} ();

doesn't work is because it's a function statement, not an expression. It's a pretty minor distinction, but basically, if the statement starts with function, it's just like a C function declaration, and you can't call the function, because there is no expression value.

Adding the parentheses makes the function definition part of an expression, so it has a value and can be called.

Assigning the return value of the function also eliminates the need for parentheses, because the function definition is not the whole statement. For example, these work:

var value = function() { alert("works"); return 0; }();
(function() { alert("works"); })();

but this doesn't:

function() { alert("doesn't work"); }();

I always include the parentheses, even when they aren't necessary because it makes it easier to see that I'm calling the function, instead of assigning it to a variable.




回答4:


As far as I know, the only difference is that the latter sometimes doesn't work in certain flavors of ECMAScript (namely ActionScript, but there could be others).



来源:https://stackoverflow.com/questions/750231/does-parenthetical-notation-for-self-invoked-functions-serve-a-purpose-in-javasc

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