Darthg8r
Darthg8r

Reputation: 12675

jquery plugin syntax wrapper

What exactly does this do? I know that it gets wrapped around jquery plugins, but have no real understanding of what it does.

(function ($, undefined) {

// Plugin goes here

})(jQuery);

Upvotes: 4

Views: 285

Answers (2)

Emre Erkan
Emre Erkan

Reputation: 8482

()() is a way to run a piece of code in javascript. The first pair of parentesis is the code part and the second is for execute order and you can pass variables like calling a function.

Within first parentesis you define your function, which takes two arguments and you execute it with a parameter jQuery which is core jQuery object. To do so, you are passing jQuery object to your function as a variable and name it $. Because your function is defined in that scope your code doesn't conflict with another $ variable on global scope or scope that contains your code.

As you can see there is another variable: undefined but no parameter for it. By not passing a second parameter second variable will be undefined and because it's name is undefined you can use it in your code freely. For more info about undefined you can look here

I hope this is clear enough.

Upvotes: 4

Kevin B
Kevin B

Reputation: 95022

That creates a scope that you can define variables and methods in without fear of them being exposed to the global scope.

There are many articles floating around going into far more detail than this.

Edit: here's one http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Upvotes: 3

Related Questions