Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why are javascript functions like this [duplicate]

Tags:

javascript

Possible Duplicate:
What does this mean? (function (x,y)){…}){a,b); in JavaScript

I am a starter to javascript. I know to write JS userdefined functions. But recently I came across some thing that I can’t recognize. Can anyone explain to me what this is?

(function( window, undefined ) {

    var jQuery = (function() {
    });
           window.jQuery = window.$ = jQuery;
})(window);

What is the meaning of this? When I Google javascript functions I am getting only

function foo(){ 
    alert("This is an alert"); 
}

I know to use these type of functions

like image 830
Kajal Avatar asked Sep 23 '12 02:09

Kajal


1 Answers

Short answer: Those are immediately invoked functions that provide lexical scope and closures.

For a better explanation please take a look at this answer I posted some time ago.

UPDATE:

Lexical scope means that variables declared within a function won't be visible outside of the function body.

Closure is a way to keep references to variables that would otherwise be out of scope, because if they were in scope where the function body was defined then it is available to any subsequent invocation of that function. See: Closure on Wikipedia.

UPDATE 2:

If you really want to understand all of these then I strongly recommend watching the 1986 Structure and Interpretation of Computer Programs MIT lectures by Gerry Sussman and Hal Abelson (available on YouTube). In my opinion there is no better way to truly understand JavaScript than watching those very lectures, even though they are not about JavaScript. You will quickly see which language was really the inspiration for Brendan Eich when he designed JavaScript. Hint: It was not Java.

like image 117
rsp Avatar answered Oct 28 '22 13:10

rsp