开发者

How do jQuery's namespaces work? [duplicate]

开发者 https://www.devze.com 2023-01-26 21:24 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: What does this JavaScript/jQuery syntax mean?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

What does this JavaScript/jQuery syntax mean?

I specifically mean when you do this:

(function ($) {
  ...
})(jQuery);

I've never seen that kind of syntax before. How does the function get开发者_开发百科 called? I understand when you do it like this:

jQuery(function ($) {
  ...
});

because the function is being passed to jQuery, and jQuery can just run any function passed as a parameter when the DOM's ready, but the first one's different.


Duplicate of What does this JavaScript/jQuery syntax mean?

I'll post my answer here, though seeing as Jeff Attwood seems to want us to embrace duplication: (https://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/)


This convention is used when writing plugins to ensure there is no confilict with other Javascript libraries using the $ notation, whilst ensuring the plugin author can still use this notataion:

(function($){
    ...
})(jQuery); 

The author is declaring an anonymous function with a single parameter ($), then immediately calling it and passing the jQuery object to it. This ensures the function is called and that everything in it is defined.

A longer notation might be:

function MyDefs($){
    ...
}
MyDefs(jQuery);

Although that would create a variable MyDefs in the global namespace. The anonymous function pattern leaves the global namespace empty, avoiding conflicts.


It's an anonymous function. When you write:

(function ($){
  ..
})(jQuery);

It is mostly equivalent to:

function the_function($) {
  ..
}

the_function(jQuery);

The only difference being that the first does not create a function called the_function and therefore created no risk of accidentally overwriting an existing function or variable with that name. And of course, all of it is equivalent to:

function the_function() {
  var $ = jQuery;
  ..
}

the_function();

The point of this construct is that any variables defined inside the_function are local and therefore cannot accidentally overwrite any variables or functions in the global scope. For instance, the code inside the function uses $ to represent the jQuery object, but this would conflict with other libraries that use $ as well (such as Prototype). By wrapping the usage of $ inside a function, the Prototype code outside the function remains unaffected.

0

精彩评论

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