0

Here is an example of a function that is followed by the jQuery function:

<script> 
    (function ($)
    {
        $('a').mouseenter(
        function () { alert(this.id); });
    })(jQuery);
</script>

I have done tons of searches and been reading through jQuery Succinctly, but I'm really struggling to understand what passing in the $ sign or following the function with (jQuery) does. Could anyone clarify this for me?

Bonus question: does this have anything to do with extending a jQuery method? I am looking into trying to extend the .html() method.

Jacob Stamm
  • 1,064
  • 1
  • 19
  • 47
  • For the bonus: [Extending an existing jQuery function](http://stackoverflow.com/questions/5007279/extending-an-existing-jquery-function) – Spokey Jan 23 '15 at 14:36
  • This is exactly the same as `var a = function($){}; a(jQuery);`, but you are just not saving the function in a variable. – Karl-André Gagnon Jan 23 '15 at 14:41

4 Answers4

2

What you have there is an function which takes a parameter called $. Then you are calling that function and passing it jQuery as the parameter. This allows you to use $ as shorthand for jQuery inside that function. It is useful when for whatever reason, you can't use $ shorthand everywhere.

James Waddington
  • 2,834
  • 2
  • 12
  • 23
2

You're passing the package jQuery in as the parameter to the function, to ensure that $ is an alias for jQuery.

Roy J
  • 37,999
  • 5
  • 58
  • 88
  • is there anytime `$` would not be an alias for jQuery? Is this scope-related? – Jacob Stamm Jan 23 '15 at 14:43
  • 1
    @JacobStamm Often in CMS like Joomla or Wordpress, `$` will not be jQuery. Hence, that closure is useful if you do not want to write jQuery every time. Also, when creating a plugin, you should always have a closure like that in case the developer using your plugin override `$` – Karl-André Gagnon Jan 23 '15 at 14:45
0

The construct is known as an IIFE - Immediately-Invoked Function Expression. The result of the expression inside the first set of parens is a function that takes one parameter (named $). The second set of parens then immediately invokes that function passing in the jQuery object.

It's a common pattern used to avoid polluting the surrounding (or global) scope.

mbcrute
  • 989
  • 1
  • 9
  • 19
0

The dollar symbol ($) is an alias for the jQuery object that is passed in to the Immediately Invoked Function Expression. It could just as easily be a different character.

Here's a little example:

/* 
 Here's my huge library akin to jQuery's (albeit with slightly less functionality). 
 */
function MySuperLibrary(){
    this.foo = function(bar){alert(bar);}
};
var msl = new MySuperLibrary;//a new instance of My Super Library

/* 
 Here I'm Immediately Invoking a function and passing the msl instance to it.
 I've used the 'X' character for its namespace within the closure in the same way as jQuery uses a $.
 */
(function(X){
    X.foo("foobar");
})(msl);
Moob
  • 13,593
  • 1
  • 29
  • 45