logic - Can someone explain this JavaScript auto executing function? -


var foo = (function(){   var x = 0;   return function(){return x++;}; })() 

why var x = 0 expression runs once biggest misunderstanding this.

your code:

var foo = (function(){   var x = 0;   return function(){return x++;}; })() 

is equivalent code:

function f(){   var x = 0;   return function(){return x++;}; } var foo = f(); 

it's easy see, when break this, function f() called once. defines x, , returns new function defined inside local scope of f. new function called "anonymous function" (meaning has no name) or "closure". in truth, all functions in javascript "closures" -- whether or not named. term "closure" means function retains access variables defined in parent function's scope -- after parent function has exited.

so now, foo contains new function (the closure) returned f. can call foo() many times -- , each time do, x returned , post-incremented. since x exists in closure's parent scope, value persist across multiple calls closure.

what's more... no other code has access x once f() has exited -- means x "private data" of closure. pretty neat huh?


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -