Last active
May 3, 2018 21:05
-
-
Save cgradwohl/378cb8f83516e020cc52aa439881506d to your computer and use it in GitHub Desktop.
another basic 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
var x = "!"; | |
var outer = () => { | |
var a = "there"; | |
var inner = () => console.log("Hey " + a + x); | |
return inner; | |
} | |
var anotherOuter = outer(); | |
x = "?"; // 'x' is lexically available to outer() and therefore also to anotherOuter(). | |
//therefore it is mutable in the context of anotherOuter(). | |
anotherOuter(); // --> "Hey there?" | |
console.log(a); // --> ReferenceError: a is not defined | |
// the function declaration of outer() creates a closure around 'a', | |
//so it is NOT available in the lexical context of anotherOuter(). | |
// 'a' is truly a private variable! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment