Created
December 31, 2014 07:04
-
-
Save industral/e7dad28f54ccb2d6df9a to your computer and use it in GitHub Desktop.
JavaScript Closure Example
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
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