jQuery函数语法差异

时间:2012-03-19 00:05:19

标签: javascript jquery

如何:

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

与jquery中的$(document).ready(function()不同?

我知道ready函数的作用。等待HTML加载才开始。但是,(function($)也这样做吗?

3 个答案:

答案 0 :(得分:3)

  

我知道ready函数的作用。等待HTML加载才开始。但是,(function($) { ... })()也这样做吗?

不,不。它在控制到达该语句时(以及何时)立即执行。

尝试运行

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

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

亲眼目睹。

答案 1 :(得分:2)

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

这是一个自动执行的匿名函数,只要javascript解释器读取它就会执行块内的代码。

这不要与以下语句混淆,后者等同于jQuery ready:

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

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

这些jQuery就绪函数只会在DOM加载完所有元素后执行(图像在慢速连接上可能需要相当长的时间)。

第一个和最后两个不相等,自执行函数将始终在jQuery ready函数之前发生,有时很长时间取决于页面的大小以及用户连接的速度。

答案 2 :(得分:1)

$(document).ready()的“速记”只是$()

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

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

但是,您的第一个代码 NOT .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的代码,而其他库使用相同的$函数名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