-4

I have a little trouble about the meaning of syntax "(function( $ )" and "(jQuery)" in the below code.

(function( $ ){
$.fn.myPlugin = function() {
    // Do your awesome plugin stuff here
};})(jQuery);

Can you please explain what meaning of them ?

If I want to change phrase "(jQuery)" in the above code to "(abc)" then how to do it and how to use it ?

Thanks for taking the time to answer my question.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    If you change `jQuery` to `abc` then `$` inside the closure will be the value of `abc` instead of `jQuery`. If `abc` is undefined `$.fn.myPlugin` will give an error. – Halcyon Oct 02 '13 at 15:34
  • 1
    And why do you want to change that to abc anyhow? – Kai Qing Oct 02 '13 at 15:36
  • 2
    Your question has already been answered [here](http://stackoverflow.com/questions/4484289/id-like-to-understand-the-jquery-plugin-syntax). – bertl Oct 02 '13 at 15:39
  • @bertl whoa, and answered by Joel himself! – Evan Davis Oct 02 '13 at 15:40
  • Check out this answer: http://stackoverflow.com/questions/12008843/start-javascript-code-with-function-etc/12008894#12008894 – Joseph Silber Oct 02 '13 at 15:41

2 Answers2

1

function($) says that the function takes a single parameter, the variable $, which (like any parameter) is accessible inside the function.

The $.fn.myPlugin is making use of that parameter.

The (function...)(jQuery) is making a function block that automatically gets invoked, passing jQuery as the parameter.

The point in doing this is making sure that the $ alias people usually use to represent jQuery actually is passed a jQuery object, and not any other variable named $.

There's no good reason to change jQuery to abc, unless you have a jQuery instantiation in the variable abc.

Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76
1

It is an immediately invoked function expression. It allows you to 1) enclose code in such a way that any variables are limited to its scope rather than polluting the window environment, and 2) to pass in parameters you can use in your code.

In this case Jquery is passed in as $ so you can use $ safe in the knowledge that you can use $ without it conflicting with any other libraries that might use it as an alias.

You can certainly pass in abc as well as jQuery assuming abc exists.

(function($, abc) {
  $.fn.myPlugin = function() {
   console.log(abc);
  }
}(jQuery, abc));
Andy
  • 61,948
  • 13
  • 68
  • 95