-1

Someone can explain me what does this code do?

(function($) {
    $.cookie = function(key, value, options) {
         // Body of the function here
    }
})(jQuery);

Wasn't is simpler just declaring in that way?

function cookie(key, value, options) {
     // Body of the function here
}
user1883212
  • 6,579
  • 9
  • 42
  • 71

2 Answers2

7

This is called a closure to avoid conflicts with other libraries which are using $. This way you can ensure to use $ in that function with passing jQuery as a param.

(function ($) {
   $(function () {
    .......
   });
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.

like Mootools, prototype etc libraries also uses $ and this closure is used to avoid any conflict.

Jai
  • 71,335
  • 12
  • 70
  • 93
4

You're creating an anonymous function that accepts $, and you're immediately invoking it, passing jQuery. That creates a closure where $ is jQuery. That is, provided that you know that jQuery will be a jQuery instance at the time of execution, you know also that $ will be a jQuery instance instance in that closure. It's a safeguard against competing frameworks that might also define $.

David Hedlund
  • 121,697
  • 28
  • 196
  • 213