Possible Duplicate:
What is the purpose of a self executing function in javascript?
What meens in JS write a code like this:
(function (window) { })(window);
or this:
(function () { })();
asked Jul 3, 2012 at 20:55
Rodrigo Reis
1,13712 silver badges22 bronze badges
-
It's a duplicate so I voted to close, though I think the answers there aren't as good as the answers here. specially not this wrong +17 answergdoron– gdoron2012年07月03日 21:14:11 +00:00Commented Jul 3, 2012 at 21:14
-
If someone looks for PHP 7, where this has been introduced. stackoverflow.com/questions/3568410/…Franz Holzinger– Franz Holzinger2019年11月15日 15:12:42 +00:00Commented Nov 15, 2019 at 15:12
3 Answers 3
It creates a closure, a private scope hiding the variables from the global object
// Somewhere...
var x = 2;
...
...
// Your code
var x = "foo" // you override the x defined before.
alert(x); // "foo"
But when you use a closure:
var x = 2;
// Doesn't change the global x
(function (){ var x = "foo";})();
alert(x); // 2
Regarding to the syntax, it's just a self executed function, you declare it and then execute it.
Sign up to request clarification or add additional context in comments.
4 Comments
Rodrigo Reis
TY! And when I pass a variable? Like this:
(function (window) { })(window);gdoron
@RigoReis. They become variables in the function. it's used for minifing code, nothing "real"
Rodrigo Reis
TY'll folks help me so much, special thanks to @gdoron
gdoron
@RigoReis. No problem. Good luck in your new js way.
It's a self invoking anonymous function or a function expression. It prevents you from creating variables in the global scope. It also calls the function right away.
function someFunc() {
// creates a global variable
}
var someFunc = function () {
// creates a global variable
}
(function(){
// creates an anonymous function and
// runs it without assigning it to a global variable
})();
answered Jul 3, 2012 at 20:57
Ufuk Hacıoğulları
38.6k14 gold badges120 silver badges157 bronze badges
Comments
lang-js