3

Possible Duplicate:
What is the purpose of a self executing function in javascript?
What does this mean? (function (x,y)){…}){a,b); in JavaScript

I see sometimes functions defined like these examples :

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

(function(param) {
    ....     
})(JQuery);

(function(chat, Friend) {
    ....     
})(chat, chat.module("friend");

After some web researches, I didn't find any information about the meaning of the last parentheses information.

Is there someone to explain how to use it? Or simply point a web link explaining the meaning?

Community
  • 1
  • 1
sdespont
  • 13,915
  • 9
  • 56
  • 97

3 Answers3

2

Suppose we had:

function add1 (x) {
    return x+1;
}

Then we might call add1(5) to get the value 6.

But with the brackets, rather than calling add1(5), we can replace it with (function (x) {return x+1;})(5). Basically this creates a function, and applies it to the value 5 immediately, whereas when we call add1(5), we are using a named/defined function.

Michael Oliver
  • 1,392
  • 8
  • 22
2

meaning of the last brakets

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

The () in the end causes the code inside the function to be executed immediately.

(function(param) {
    ....     
})(JQuery);

The (JQuery) in the end causes the code inside the function to be executed immediately, passing JQuery as a parameter to it.

(function(chat, Friend) {
    ....     
})(chat, chat.module("friend"));

The (chat, chat.module("friend")) in the end causes the code inside the function to be executed immediately, passing chat and chat.module("friend") as parameters to it.

Nope
  • 22,147
  • 7
  • 47
  • 72
0

Check out this question: What is this practice called in JavaScript?

Basically, the function will execute with the parameters you pass it. In this example, param will have the value of jQuery:

(function(param) {
    ....     
})(JQuery);
Community
  • 1
  • 1
KaeruCT
  • 1,605
  • 14
  • 15
  • It should be an error. The line `})(JQuery);` would be valid, as would `}(JQuery));`, but not `})(JQuery));` unless your starting function statement looks like `((function ($) {` for no reason. – Norguard Dec 31 '12 at 16:02