Skip to content

Instantly share code, notes, and snippets.

@fengye
Last active January 20, 2016 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fengye/05dad798112d38d5c3e3 to your computer and use it in GitHub Desktop.
Save fengye/05dad798112d38d5c3e3 to your computer and use it in GitHub Desktop.
How JavaScript closure works
//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