Why javascript functions like this

Possible duplicate:
What does this mean? (function (x, y)) {...}) {a, b); in javascript

I am a starter for javascript. I know to write custom JS functions. But recently, I came across something that I can’t understand. Can someone 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 work on Google javascript, I only get

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

I know how to use these types of functions

+5
source share
3 answers

Short answer: these functions immediately call functions that provide a lexical scope and closure.

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

UPDATE:

, , , .

- , , , , , . .: .

2:

, 1986 a > MIT Gerry Sussman Hal Abelson (, YouTube). -, - JavaScript, , JavaScript. , , JavaScript. : Java.

+4

, , .

public private, , , , , ,

, , , :

var a = (function() {
  var a= 0; // this is only accessible inside this function
  var b = {
    a: 1 // this will be returned and therefore be accessible on the outside
  };
  return b;
})();

console.log(a.a); // outputs 1
+3

. .

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

() :

foo();

(, **, . **). , rvalue,

var f = function (){ 
    alert("This is an alert"); 
};

() :

f();

:

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

, ! (.. ).

:

(function( window, undefined ) {
    //blah blah blah -1
    //blah blah blah -2
})(window);

:

var f = function( window, undefined ) {
    //blah blah blah
};
f(window);

( f) 2 : window undefined. 1- window ( , ). , . , , Javascript undefined ( ). , () undefined undefined.

- . ( , , - JS script undefined - !)

See: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Functions https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Expressions_and_Operators

EDIT:

As @FelixKling comments, function expressions need not be anonymous; they may have names.

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

This is an interesting article about their use.

+1
source

All Articles