Created
February 5, 2012 06:14
-
-
Save deletosh/1743447 to your computer and use it in GitHub Desktop.
best explanation of Javascript Closure, ever
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Here is a case that might surprise you: | |
var variable = "top-level"; | |
function parentFunction() { | |
var variable = "local"; | |
function childFunction() { | |
print(variable); | |
} | |
return childFunction; | |
} | |
var child = parentFunction(); | |
child(); | |
parentFunction returns its internal function, and the code at the bottom calls this function. Even though parentFunction has finished executing at this point, the local environment where variable has the value "local" still exists, and childFunction still uses it. This phenomenon is called closure. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment