0

This is partly a jquery question, but most javascript. I just don't know javascript well enough to understand this code:

1 (function () {
2            $(function () {
3                //Global ajax progress dialog box
4                //Simply run $("#ajax-progress-dialog").dialog("open"); script before the ajax post and
5                //$("#ajax-progress-dialog").dialog("close"); on the ajax post complate
6                $("#ajax-progress-dialog").dialog({
7                    autoOpen: false,
8                    draggable: false,
9                    modal: true,
10                    height: 80,
11                    resizable: false,
12                    title: "Processing, please wait...",
13                    closeOnEscape: false,
14                    open: function () { $(".ui-dialog-titlebar-close").hide(); } // Hide close button
15                });
16            });
17        })(); 

I understand lines 3-15. In fact, I think I understand lines 2 through 16: this is creating an anonymous function and wrapping it as a jquery object, right? Not sure why it needs to be wrapped, but more importantly, I especially don't understand lines 1: opens with "(function" and 17: closes with ")()". What's that about?

BTW, for completeness, note that this is invoked as follows:

$("#ajax-progress-dialog").dialog("open");

Credit: this example comes from tugberkugurlu

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
Elroy Flynn
  • 3,032
  • 1
  • 24
  • 33
  • Actually, I think you can go ahead and delete lines 1 and 17 as it does the exact same thing as lines 2 and 16. Don't know why they've put it twice – Tom Jan 21 '12 at 22:07
  • Pretty sure this has been asked several times. Google up `self invoking anonymous function`. Let me try to find a duplicate. – Anurag Jan 21 '12 at 22:08

5 Answers5

1

It basically creates an anonymous function and runs it immediately. This is useful for creating a closure, for example to run code with var x, y, z without polluting the current (usually global) scope.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

It is a self executing function, basically it keeps everything inside of it out of the global scope. Explained in the thread: What is the purpose of a self executing function in javascript?

But in this example code you shown it is not needed. The document ready call of

$( function(){
    ...
});

does the same exact thing.

Community
  • 1
  • 1
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • What would be different if it were simply the following? What variables/objects would have greater scope than they should? `$("#ajax-progress-dialog").dialog({ autoOpen: false, draggable: false, modal: true, height: 80, resizable: false, title: "Processing, please wait...", closeOnEscape: false, open: function () { $(".ui-dialog-titlebar-close").hide(); } });` – Elroy Flynn Jan 22 '12 at 01:16
  • And if someone could explain how to format the code of my preceding comment I'd appreciate it. I put 2 spaces at the end of each line like the doc says, but that didn't work. – Elroy Flynn Jan 22 '12 at 02:40
  • Nothing would have window scope in your question above. $() is a short cut for [document ready](http://api.jquery.com/ready/) – epascarello Jan 23 '12 at 01:05
0

When $() is called with an anonymous function, the given anonymous function is called once the DOM is ready. It's a shortcut for $.ready(). See http://api.jquery.com/ready/ for information on it.

As for the first and last lines, I believe it's declaring another anonymous function, and then immediately calling it. I'm not entirely why that would be different from just writing the content of the function, though.

Edit: Kolink is right, that would be used to restrict the scope. However, that doesn't seem to have any benefit in this particular example.

TLUL
  • 11
  • 1
0

This method is used for creating a closure and 'protecting' your variables.

http://jibbering.com/faq/notes/closures/

mbx-mbx
  • 1,765
  • 11
  • 23
0

It's not a jQuery specific thing, but it's called a closure. It means anything you use inside it remains within the scope of that closure, so it won't conflict with code used elsewhere (important when you're using lots of scripts or jQuery plugins).

You might see examples that pass in the window and document parameters, as a document ready equivalent:

(function(document, window) {
    var closure_test = 'Hello world!'

    console.log(window.location.href, closure_test);

})(document, window);

console.log(closure_test);

Run this through Chrome's JS console (or Firebug), and you'll notice that closure_test is accessible inside the closure, but is undefined outside of it.

There's a lot more you can do with it, that your sample code doesn't demonstrate. Eg. using it to imitate a class without using prototypes:

var exClass = (function() {

    function private() {
        return 'I am private';
    }

    // return an object of functions or properties we want to expose
    return {
       public: function() {
           return 'I am publicly accessible';
       }
    }
})();

console.log(exClass.public());
// I am publicly accessible

console.log(exClass.private());
// object has no method 'private'

console.log(private());
// undefined

Notice how you can't get to the function called private, but you can use the one called public().

leemeichin
  • 3,339
  • 1
  • 24
  • 31