1. 程式人生 > >javascript中(function(){})($)與$(function)的區別

javascript中(function(){})($)與$(function)的區別

之前一直沒弄清楚這兩者的區別,只是發現多個(function(){})($)之間定義的方法是可以互通的,以為這個會比較好,實際運用中發現並不是這麼簡單的。

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() {/*...*/}();

在需要表示式的場景下,就不需要用括號括起來了:

void function(){/*...*/}();

var foo = function(){/*...*/}(); 

true && function () { /*...*/ }();

0, function () { /*...*/ }();1234567

void聲明瞭不需要返回值,第二個則將IIFE函式的返回值賦給了foo。第三、第四個都是明確需要表示式的場景,所以解析器會認識這種寫法。

對於IIFE函式,也可以給它們傳入引數,例如:

(function foo(arg1,arg2,...){...}(param1,param2,...));1

對於常見的(function( $ ){...})(jQuery);即是將實參jQuery傳入函式function($){},通過形參$接收。 上述函式中,最開始的那個括號,可能會由於js中自動分號插入機制而引發問題。例如:

a  =  b  +  c 
;function  () { 
  // code 
})();1234

如果沒有第二行的分號,那麼該處有可能被解析為c()而開始執行。所以有的時候,可能會看到這樣的寫法:;(function foo(){/*...*/}()),前邊的分號可以認為是防禦型分號。

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

$ (function(){/*...*/});$(document).ready(function(){/*...*/})的簡寫形式,是在DOM載入完成後執行的回撥函式,並且只會執行一次。

$( document ).ready(function() {
   console.log( "ready!" );
});   123

$(function() {
   console.log( "ready!" );
});123

起到的效果完全一樣。

在一個頁面中不同的js中寫的$(function(){/*...*/});函式,會根據js的排列順序依次執行。 例如: test.html

<!DOCTYPE html> 
<html> 
<head></head> 
<body> 
    <span>This page is shown to understand '$(document).ready()' in jQuery. <br /><span> 
    <p> 
        If you see this line, it means DOM hierarchy has been loaded. NOW loading jQuery from server and execute JS...<br /><br /> 
    </p> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script src="test1.js"></script>
    <script src="test2.js"></script>
</body> 
</html>12345678910111213

test1.js

$(function(){
    $(document.body).append("$(document).ready()1 is now been executed!!!<br /><br />"); 
});123

test2.js

$(function(){
    $(document.body).append("$(document).ready()2 is now been executed!!!<br /><br />"); 
});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!!!

轉載自:這篇部落格