What are the differences between these three types of module pattern?

ぐ巨炮叔叔 提交于 2019-11-28 08:31:06

问题


1)function () { 
    // code here...

}();

2)(function () { 
    // code here...

})();



3)(function () { 
    // code here...

}());

What are the differences (especially third variant)? Are they all the same?


回答1:


First one gives a syntax error. Second and third versions define a anonymous function and immediately execute it. Second and third versions are also called Immediately Invoked Function Expressions.

You might also encounter another version which looks like this. This is equal in functionality to 2nd and 3rd version but it just negates the return value.

!function() {
   //some code
}()



回答2:


2 and 3 are exactly equivalent. There is no functional difference between them.

1 is a syntax error. Because the function is not wrapped in brackets, it is treated as a function declaration. It is invalid because function declaration need to be named. The brackets make it a "function expression"; these do not need to be named.




回答3:


1st one is not valid, however you can do following instead to make it work:

var myfunction = function () { 
    // code here...
}();

As other answers pointed out that there is no difference between 2nd and third, they are same.

Instead of using parenthesis, following is also valid:

!function() { /*  code here... */ }();
~function() { /*  code here... */ }();
+function() { /* code here... */ }();
-function() { /*  code here... */ }();
new function() { /*  code here... */ };
new function(arguments) { /*  code here... */ }(arg);

Note: People used to call these functions 'Self-Executing Anonymous Function' but the term is incorrect. Now they are called 'Immediately Invoked Function Expressions (IIFE)' pronounced "iffy"!



来源:https://stackoverflow.com/questions/7647019/what-are-the-differences-between-these-three-types-of-module-pattern

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