Last active
January 20, 2016 14:59
-
-
Save fengye/05dad798112d38d5c3e3 to your computer and use it in GitHub Desktop.
How JavaScript closure works
This file contains hidden or 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
//From http://stackoverflow.com/questions/111102/how-do-javascript-closures-work | |
function sayHello2(name) { | |
var text = 'Hello ' + name; // Local variable | |
var say = function() { console.log(text); } | |
return say; | |
} | |
var say2 = sayHello2('Bob'); | |
say2(); // logs "Hello Bob" | |
// The above code has a closure because the anonymous function function() { console.log(text); } | |
// is declared inside another function, sayHello2() in this example. In JavaScript, if you use the | |
// function keyword inside another function, you are creating a closure. | |
/* | |
* Whenever you use function inside another function, a closure is used. | |
* Whenever you use eval() inside a function, a closure is used. The text you eval can reference local | |
variables of the function, and within eval you can even create new local variables by using eval('var foo = …') | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment