JavaScript self-invoking functions [duplicate]

不羁岁月 提交于 2019-12-06 03:06:12

问题


Possible Duplicate:
Difference between (function(){})(); and function(){}();
Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?

I just wondered whether there is a difference (regarding the functionality) between these two examples:

1st

(function foo() {
console.log("bar")
})()

2nd

(function foo() {
console.log("bar")
}())

Both seem to work fine ...

Thanks!


回答1:


They are exactly the same. There is no difference whatsoever between the two in terms of efficiency, output, or use. Using either one is a matter of preference.

Though there is a shorter variation of the two forms commonly used by JS minfiers. That is, logical NOT-ing the function expression and calling it:

!function() {
    console.log( x );
}();​



回答2:


No difference. In fact, you need to use () only because plain...

function() { console.log('bar'); } ();

... won't be properly recognized by JS parser. As said in the ES5 standard:

Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

The alternative (to (...)) solution is augmenting this statement with some unary operator. Both...

+function() { console.log('bar'); } ();

... and ...

!function() { console.log('bar'); } ();

... will work.




回答3:


There's no difference between them. Both are immediately invoked function expressions. Some people like Douglas Crockford prefer the second method. Some prefer the first. Interestingly Crockford's JSLint doesn't allow the first method, so I assume that the second one is more common.

Oh, and if you use a function declaration instead of a function expression then you can call the function before it appears in the program. This is because declarations are hoisted in JavaScript:

greet(); // This will work

function greet() {
    alert("Merry Christmas!");
}

The same is not true for function expressions:

greet(); // This will not work

var greet = function greet() {
    alert("Merry Christmas!");
};

That's pretty much all you need to know for now.



来源:https://stackoverflow.com/questions/14011509/javascript-self-invoking-functions

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