var foo = (function(){
var x = 0;
return function(){return x++;};
})()
Why the var x = 0 expression only runs once is my biggest misunderstanding about this.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your code:
is equivalent to this code:
It’s easy to see, when you break it up like this, that the function
f()is only called once. It definesx, and then returns a new function that is defined inside the local scope off. This new function is often called an “anonymous function” (meaning that it has no name) or a “closure”. In truth, all functions in javascript are “closures” — whether or not they are named. The term “closure” simply means that the function retains access to the variables that were defined in the parent function’s scope — even after the parent function has exited.So now,
foocontains the new function (the closure) that was returned fromf. You can callfoo()as many times as you like — and each time you do,xwill be returned and post-incremented. Sincexexists in the closure’s parent scope, its value will persist across multiple calls to the closure.What’s more… no other code now has access to
xoncef()has exited — this basically means thatxis now the “private data” of the closure. Pretty neat huh?