Skip to content

Instantly share code, notes, and snippets.

@industral
Created December 31, 2014 07:04
Show Gist options
  • Save industral/e7dad28f54ccb2d6df9a to your computer and use it in GitHub Desktop.
Save industral/e7dad28f54ccb2d6df9a to your computer and use it in GitHub Desktop.
JavaScript Closure Example
window.x = 1; // will controll external variable
(function() {
var a = window.x / 2; // lexical scope, evaluate within external variable
var b = window.x * 2;
window.AAA = function A() {
console.log(a + b); // use lexical variables
}
})();
AAA(); // result === 2.5, as x = 1
window.x = 2; // change x = 2
AAA(); // the same result (2.5), as closure means saving lexical scope.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment