开发者

jQuery $ function syntax

开发者 https://www.devze.com 2023-03-10 08:32 出处:网络
What i开发者_StackOverflow社区s the difference between the following function definitions? 1: $(function () {

What i开发者_StackOverflow社区s the difference between the following function definitions?

1:

$(function () {
    //stuff here
}); 

2:

function($){
    //stuff here
}


In #1, your function will be called by jQuery when the DOM is ready; passing a function into $() is a shortcut for $(document).ready(function() { ... }); (details here).

In #2, you're defining a function but neither calling it nor asking jQuery to call it. (And in fact, as shown, it's a syntax error — you'd need to be assigning it to something or calling it for it to be valid without a name.) Nothing you've quoted will execute the function, you'd have to call it yourself.

On #2, the idiom you've probably seen there is:

(function($) {
    // ...code using `$` for jQuery here...
})(jQuery);

That's fairly standard thing you'd do when you want the code to run immediately (not wait for DOM ready), and you want to use $ within the function to refer to jQuery, but you want to be compatible with noConflict mode. You see this a lot in plug-ins. It defines a function accepting a $ argument, which shadows any $ defined globally, and then immediately calls that function passing in jQuery as the argument. So even if $ doesn't map to jQuery globally, it does within that function. You can do the same thing like this:

(function() {
    var $ = jQuery;
    // ...code using `$` for jQuery here...
})();

...but for some reason the earlier example is more common, even if a bit less clear. (It's a couple of characters shorter, I suppose.)


  1. This code calls the function $ with anonymous function as the first argument. Usually it is used to do something when page is loaded (or better say DOM is ready). And yes it will do some stuff, but only when event will be fired.

  2. This code is just a declaration of anonymous function with one argument $. You can often find such functions in the code of jQuery plugins. Such technique is useful to have $ variable locally. This will improve performance a bit and help not to pollute global scope.

So the first snippet will make some action being executed and the second will do nothing useful.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号