TK.
TK.

Reputation: 28153

Understanding a skeleton of jQuery plugin

At a website, I found the following code to make a jQuery plugin:

(function($){
  // Our code here...
})(jQuery);

I don't understand how the code above works. What I understand is that the code executes immediately because the very last () in function(){}(). So the entire code says that is an anonymous function that is run immediately.

But I don't understand why the wrapping needs to pass jQuery and that inside it needs $ to be passed.

From my understanding, $ is an alias to jQuery, meaning practically the same. What is the meaning of $ and jQuery here? How does the overall code work as a jQuery plugin?

Upvotes: 3

Views: 537

Answers (4)

Sean
Sean

Reputation: 15961

Gnarf brought up global scope pollution of vars, I would add of functions as well.

You might want to use a helper function like:

(function($){
  // Our code here...
  $.fn.myPluginFunction = function () {
    ...
    var x = foobalizeTheFrobmaster(this.offset())
    ...
  }

  function foobalizeTheFrobmaster(pos) {
    // do something useful
    return something;
  }
})(jQuery);

This way the internal function foobalizeTheFrobmaster() is completely hidden in our closure.

Upvotes: 0

gnarf
gnarf

Reputation: 106332

In order to be maximally compatible with other libraries as well, jQuery offers .noConflict(). This removes the $ alias from the global namespace so another library could use it if you want.

If you don't want your plugin to work with .noConflict() it's not necessary.

Using the closure also allows you to not pollute the "global scope" with var's

Upvotes: 0

Anurag
Anurag

Reputation: 141869

jQuery is the actual parameter. $ is the formal parameter. You could very well write:

(function(ForAFewDollarsLess){
    ForAFewDollarsLess('#myId') ...
})(jQuery);

One reason is convenience - it's short. You might be using jQuery in noConflict mode with other libraries. Maybe typing jQuery all the time is a hassle, or other plugins are following bad practices and using $ instead of jQuery. Either ways, you can use a self-calling function like the one above to solve the problem.

Upvotes: 3

Sarfraz
Sarfraz

Reputation: 382666

You pass the alias $ in function so that it will always refter to JQuery actually. If there are some other libraries included in a certain page such as prototype which also uses $, your code won't break and will work fine.

Upvotes: 0

Related Questions