Skip to content Skip to sidebar Skip to footer

In Javascript, What Does This Syntax Mean?

I found this snippet when i was looking at jQuery plugins and wonder what it actually does A jQuery plugin skeleton: (function($) { ... })(jQuery); And more recently in nett

Solution 1:

This creates a anonymous function and calls it directly: this is equivalent to

varfun = function(){};
fun();

its used in jquery plugins to ensure compatibility with other libraries defining a global variable '$'. in your plugin sekeleton, you wrap your plugin in a anonymous function, which receives an argument named '$' (thus overriding a global variable '$'), this anonymous function is then called with 'jQuery' as parameter, so effectively $ becomes = jQuery, but only within that anonymous function.

Solution 2:

The first part:

function($) {
    ... 
}

creates an anonymous function. The second part: wrapping this function with braces and (jQuery); cal the function with jQuery as argument (usable via $ in the function).

nettuts then saves the result of the call in the variable.

Solution 3:

The first function means that $ is overwritten by jQuery, which is useful if you have given a different meaning to '$' in the script.

Post a Comment for "In Javascript, What Does This Syntax Mean?"