Created
December 9, 2014 21:32
-
-
Save nulayuhz/51b2cf02a1618ceff462 to your computer and use it in GitHub Desktop.
closure
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
https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch5.md | |
Closure is when a function is able to remember and access its lexical scope even | |
when that function is executing outside its lexical scope. | |
function foo() { | |
var a = 2; | |
function bar() { | |
console.log( a ); // 2 | |
} | |
bar(); | |
} | |
foo(); | |
1. lexical scope look-up rules (nested function scope) can kind of explains how function bar() has access to | |
the variable a in the outer enclosing scope. | |
2. but "From a purely academic perspective, what is said of the above snippet is that the function bar() | |
has a closure over the scope of foo() (and indeed, even over the rest of the scopes it has access to, | |
such as the global scope in our case). Put slightly differently, it's said that bar() closes over the | |
scope of foo(). Why? Because bar() appears nested inside of foo(). Plain and simple. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment