tags:

views:

104

answers:

3

Can anyone explain what the jquery documentation is exactly referring to with this statement: "the argument to write failsafe jQuery code using the $ alias, without relying on the global alias" when referring to using the following:

    jQuery(function($) {
});

I have been using jquery for a while now so understand what this code is doing to a certain extent but the phrase used in the documentation about writing failsafe jquery code puzzles me and i am unsure whether it is important or not.

+3  A: 

Failsafe is just referring to the possibility that some other code or library might also try to use the $ as a var name. It's far less likely that another library would use the name jQuery, so by encapsulating everything in a function and passing jquery as the arguemnt ($), you are safe to use the $.

Rookwood
+1  A: 

The $ variable name is not unique to jQuery - other javascript libraries also make use of it. If you are using both on the same page (perhaps not intentionally - another library could be pulled in by a third party script) then there is a risk that the variable you think points to a jQuery object actually points to something else meaning your code will break as the API you are working to won't exist.

What this code does is use the global jQuery function (which doesn't clash with any other library) to which is passed an anonymous function receiving the main jQuery object as a parameter. Because this parameter is scoped to the function and not globally, nothing outside the function can interfere with it, and you can code with it safe in the knowledge that it will only ever be a jQuery object unless you override it yourself.

Luke Bennett
+3  A: 

The notion is related to when creating plugins, when you can't for example be sure that $ is an alias for the jQuery object. The failsafe way is to either exclusively use jQuery directly, or wrap it in a closure if you want to be able to use $in your plugin code:

(function($){
  // here code can always use $ as n alias for jQuery, regardless if the user
  // has repointed $ to something else.
})(jQuery);
azatoth