开发者

jQuery / javascript wrapped code query

I have inherited some jav开发者_开发技巧ascript code that is wrapped in the following way:

(function ($) {
    //some javascript using jQuery here...               
} (jQuery));

What does it do?


It invokes an anonymous function immediately, passing in the global jQuery as an argument to the function call, which is then referenced by the $ parameter.

This ensures that $ is local to that function so it won't conflict if some other library is using the global $ identifier.

Think of it like this:

   // create a function that receives jQuery as an argument
function keepItLocal( $ ) {

    // execute your jQuery code in here
    //   where $ is now a reference to jQuery     

};

   // invoke the function, passing in the global jQuery
keepItLocal( jQuery );

Because the only way to scope a variable in JavaScript is in a function, this is a common pattern to prevent pollution of the global namespace.

If we just did this:

$ = jQuery;

$('.someClass').someMethod();

...we may be overwriting $ if it was previously defined, or some other code may come along and overwrite it.


This is an alaising closure for jQuery. it works by creating an anonymous function:

function ($)
{

}

And then wrapping it to to be called immediately with the parameter jQuery

(
  function($)
  {

  }
)(jQuery);

Which forces $ to have the value of jQuery without defaulting to window.$ which may have been overwritten by another library.

It is a common shortcut used for plugins to extend jQuery.

Additionally the document.ready event has a similar aliasing shortcut:

jQuery(function($){

});

In this case, a function is passed to the jQuery factory method (jQuery or $) to be exectued on the document.ready event. The parameter will be jQuery but it allows the developer to rename the alias to whatever they prefer, which usually is the $ shortcut.


That's the standard pattern for writing a jQuery plugin: http://docs.jquery.com/Plugins/Authoring


I'd would argue that the use a closure (the code you posted is a closure) helps to avoid collisions in variables with other parts of your code.

As described by James, plugins are written in this way precisely because of this reason.

By the way, usually a closure is written as

(function ($) {
// do something cool here!
})(jQuery);


Thats the way how to write the customized plugins in jquery

http://docs.jquery.com/Plugins/Authoring

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜