0

Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I have seen this kind of code specially when dealing with jQuery plugins. Can someone please explain me what this does?


(function(){
   //Stuff goes here....
}());
Community
  • 1
  • 1
Enrique Moreno Tent
  • 21,095
  • 29
  • 89
  • 173
  • This technique primarily has to do with scoping variables so you don't have a bunch of variables declared in the global scope, but you don't necessarily need a function or object method. – Jared Farrish Nov 26 '11 at 00:53

3 Answers3

3

They are defining a function in Javascript between the braces (the stuff goes here part would be the code to be executed) and then immediately executing it using the open and closed parens. This doesn't have to do with JQuery, it is just an anonymous function in javascript. the function(){} returns a function object which is then executed by the open and closed parens.

Chris
  • 10,888
  • 18
  • 82
  • 142
  • Then why not execute directly the code without the function? – Enrique Moreno Tent Nov 26 '11 at 00:56
  • 3
    @Dbugger if you use a function you get function scope. and function scope is bound to the function so you can have local variables that _you do not put in global scope_ – Raynos Nov 26 '11 at 01:02
  • 1
    @Dbugger Like Raynos said, it is about effectively managing variables. So as soon as the function exits, its variables are deleted so you can use their names elsewhere and the memory is freed up – Chris Nov 26 '11 at 01:06
  • I see. Usually I would make a non-anonymous funciton and then call it, but I guess this way is cleaner. Thanks! – Enrique Moreno Tent Nov 26 '11 at 01:06
  • @Dbugger yep. Kind of similar to using throwaway variables like `i` in for loops. In Javascript there are a lot of throwaway functions written like this, especially to handle callback requests – Chris Nov 26 '11 at 01:11
2

Generally, when you run into this pattern in JavaScript, it's someone attempting to make use of the module pattern. The pattern is generally considered a good way to protect your own code from interacting poorly with other libraries you may be using on your page (if you're coding in a web page).

See:

http://yuiblog.com/blog/2007/06/12/module-pattern/

Note, the wrapping parentheses at the beginning and end of the anonymous function declaration in the example code are not actually necessary. Paul Irish, in the video linked below, believes these are often included as a heads up to anyone reading the code that the code is meant to be self-contained, and not just procedural code.

By this I mean:

function(){
   //Stuff goes here....
}();

Is just as valid as:

(function(){
   //Stuff goes here....
}());

And:

(function(){
   //Stuff goes here....
})();

And:

!function(){
   //Stuff goes here....
}();

Et cetera.

Paul Irish talks about this pattern in this video:

http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

Jared Farrish
  • 46,034
  • 16
  • 88
  • 98
Bert
  • 70,407
  • 13
  • 164
  • 146
  • *The wrapping parentheses in your code are not actually necessary* I'm not sure that I agree with this statement. `:)` – Jared Farrish Nov 26 '11 at 01:05
  • What purpose do you think it serves? Take a look at http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/ starting at 2:40 or so. – Bert Nov 26 '11 at 01:07
  • Establish a non-global scope without creating an ad-hoc function or object method. Why do you think it's not necessary? If you can provide a more explanatory response, maybe I could agree. There are other uses than just for creating modules (such as running a function call or series of function calls which need to share variables but need to be specifically scoped). – Jared Farrish Nov 26 '11 at 01:11
  • @Jared Farrish: does the video I added help? – Bert Nov 26 '11 at 01:12
  • I have to watch a video to understand your statement? – Jared Farrish Nov 26 '11 at 01:14
  • @Jared Farrish: perhaps the edit to the answer helps. – Bert Nov 26 '11 at 01:15
  • That's a lot better. That's a better answer. `:)` – Jared Farrish Nov 26 '11 at 01:16
  • Also, in case that blog post one day disappears, maybe the Vimeo video link will still work: http://vimeo.com/12529436 – Jared Farrish Nov 26 '11 at 01:19
  • I edited your answer (after watching the video) and included more information and examples. – Jared Farrish Nov 26 '11 at 02:36
1

This pattern is mainly used to control the visibility of variables. For example,

var SomeObject = (function() {
    var test = "Some val"; // this will be a private variable

    function testFunction() { // this will be a private function
    }

    return {
        anotherVariable : "Hello", // this will be a public variable

        anotherFunction : function() { 
            // this will be a public function that can be called from the object
            // and can access the private properties 'test' and 'testFunction'
        }
    }
})(); 

Read more about the module pattern here.

jQuery plugins often do something like this :

(function($){
    $.fn.pluginName = function() {
        // plugin code here
    };
})(jQuery);

This is done to make sure that there is no conflict between jQuery and other JS libraries.

Hope this helps.

pradeek
  • 19,141
  • 2
  • 29
  • 32