1. (function(){}())与(function(){})()

这两种写法,都是一种 立即执行函数 的写法,即IIFE (Immediately Invoked Function Expression)。这种函数在函数定义的地方就直接执行了。
通常的函数声明和调用分开的写法如下:
function foo() {//} // 这是定义,Declaration;定义只是让解释器知道其存在,但是不会运行。 foo(); // 这是语句,Statement;解释器遇到语句是会运行它的。 123
普通的函数声明function foo(){}是不会执行的。这里如果直接这样写function foo(){}()解释器会报错的,因为是错误的语法。
IIFE函数的调用方式通常是将函数表达式、它的调用操作符、分组操作符放到一个括号内,来告诉解释器这里有一个需要立即执行的函数。否则通常情况下,解析器遇到一个function关键字,都会把它当做是一个函数声明,而不是函数表达式。
如下几种写法都是可以的:
(function foo(){//}()); (function foo(){//})(); !function foo() {//}(); +function foo() {//}(); -function foo() {//}(); ~function foo() {//}(); 1234567891011
在需要表达式的场景下,就不需要用括号括起来了:
void function(){//}(); var foo = function(){//}(); true && function () { // }(); 0, function () { // }(); 1234567
void声明了不需要返回值,第二个则将IIFE函数的返回值赋给了foo。第三、第四个都是明确需要表达式的场景,所以解析器会认识这种写法。
对于IIFE函数,也可以给它们传入参数,例如:
(function foo(arg1,arg2,…){…}(param1,param2,…)); 1
对于常见的
(function( $ ){…})(jQuery); 1
即是将实参jQuery传入函数function( $ ){},通过形参 $ 接收。
上述函数中,最开始的那个括号,可能会由于js中自动分号插入机制而引发问题。例如:
a = b + c ;(function () { // code })(); 1234
如果没有第二行的分号,那么该处有可能被解析为c()而开始执行。所以有的时候,可能会看到这样的写法:;(function foo(){//}()),前边的分号可以认为是防御型分号。

2. 第二类是$(function(){});

( f u n c t i o n ( ) / ∗ . . . ∗ / ) ; 是 (function(){//});是(function()/∗…∗/);是(document).ready(function(){//})的简写形式,是在DOM加载完成后执行的回调函数,并且只会执行一次。
$( document ).ready(function() { console.log( “ready!” ); }); 和 $(function() { console.log( “ready!” ); }); 123456789
起到的效果完全一样。
在一个页面中不同的js中写的$(function(){//});函数,会根据js的排列顺序依次执行。
例如:
test.html
<!DOCTYPE html> This page is shown to understand ‘$(document).ready()’ in jQuery.

If you see this line, it means DOM hierarchy has been loaded. NOW loading jQuery from server and execute JS…

12345678910111213
test1.js
$(function(){ $(document.body).append(“$(document).ready()1 is now been executed!!!

“); }); 123
test2.js
$(function(){ $(document.body).append(“$(document).ready()2 is now been executed!!!

“); }); 123
最后可以看到页面输出如下:
This page is shown to understand ‘$(document).ready()’ in jQuery. If you see this line, it means DOM hierarchy has been loaded. NOW loading jQuery from server and execute JS… $(document).ready()1 is now been executed!!! $ (document).ready()2 is now been executed!!!