Skip to content

Instantly share code, notes, and snippets.

@nulayuhz
Created December 9, 2014 21:32
Show Gist options
  • Save nulayuhz/51b2cf02a1618ceff462 to your computer and use it in GitHub Desktop.
Save nulayuhz/51b2cf02a1618ceff462 to your computer and use it in GitHub Desktop.
closure
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