javascript tutorial - [Solved-5 Solutions] How do javascript closures work - javascript - java script - javascript array
Problem:
Explain JavaScript Closure ?
Solution 1:
Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them!
This article is intended for programmers with some programming experience in a mainstream language, and who can read the following JavaScript function:
Solution 2:
This example shows that the local variables are not copied they are kept by reference
Solution 3:
All three global functions have a common reference to the same closure because they are all declared within a single call to setupSomeGlobals()
.
Solution 4:
This one is a real gotcha for many people, so you need to understand it. Be very careful if you are defining a function within a loop: the local variables from the closure do not act as you might first think.
Solution 5:
This example shows that the closure contains any local variables that were declared inside the outer function before it exited. Note that the variable alice
is actually declared after the anonymous function. The anonymous function is declared first; and when that function is called it can access the alice
variable because alice
is in the same scope (JavaScript does variable hoisting). Also sayAlice()()
just directly calls the function reference returned from sayAlice()
— it is exactly the same as what was done previously but without the temporary variable.