2012-03-19 57 views
2

如何:jQuery函數語法差異

(function($) { 
     /// code 
})(jQuery) 

jQuery中從$(document).ready(function()有什麼不同?

我知道ready函數是做什麼的。它會一直等到HTML加載完成後再啓動。但是,(function($)也一樣嗎?

+1

可能重複[這些jQuery的準備功能之間的區別是什麼?(HTTP: //stackoverflow.com/questions/2662778/what-is-the-difference-between-these-jquery-ready-functions) – epascarello 2012-03-19 00:11:30

回答

1

的 「速記」 爲$(document).ready()簡直是$()

//both do the same thing 
$(document).ready(function(){ 
    //run when DOM is ready 
}); 

$(function(){ 
    //run when DOM is ready 
}); 

然而,你的第一個代碼是一樣.ready()。你有什麼是immediately-invoked function expression (IIFE),或外行的方面,「立即運行該功能」

//both are the same 
(function($) { 
    //run stuff here immediately! 
})(jQuery) //arguments outside wrapping parenthesis 

(function($) { 
    //run stuff here immediately! 
}(jQuery)) //arguments inside wrapping parenthesis 

這剛好等於像這樣「功能和通話」,但函數名(匿名函數)和呼叫:

function functionWithNoName($){ 
    //"jQuery" in the call is "$" in here 
} 
functionWithNoName(jQuery) 

此方法通常用於保護使用$ jQuery的,而其他的LiBr代碼aries使用相同的$函數名稱,thus prevent conflicts。jQuery的只是使用$的速記別名jQuery(你不想鍵入jQuery('selector')所有的時間,$('selector')較短)的

(function($) { 
    //run jQuery using the "$" safely in here 
}(jQuery)) 
//while some other libraries like mootools use "$" out here 
3

我知道ready函數的作用。它會一直等到HTML加載完成後再啓動。但是,(function($) { ... })()也一樣嗎?

不,它不。它在(和每當)控制達到該語句時立即執行。

嘗試運行

$(document).ready(function() { alert('happens second'); }); 

(function($) { 
    alert('happens first'); 
})(jQuery); 

看到這樣的第一手資料。

2
(function($) { 
     /// code 
})(jQuery) 

這是一個自動執行的匿名函數,只要JavaScript解釋器讀取它就會執行塊內的代碼。

這不是要與下面的語句,這相當於jQuery的準備困惑:

$(function() { 
    // code 
}); 

$(document).ready(function() { 
    // code 
}); 

這些jQuery的準備職能將DOM後,只執行已完成加載的所有元素(圖片可以採取相當長時間連接速度慢)。

第一個和最後兩個不相等,自執行函數將始終發生在jQuery就緒函數之前,有時很長時間取決於頁面的大小和用戶連接的速度。