Last active
January 14, 2016 16:42
-
-
Save iwek/4576677 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
function f(y) { | |
var z = 1; | |
return function g(y) { | |
alert(y + z); | |
} | |
} | |
var z=10; | |
f(); //returns the function: function g(y) {alert(y + z);} | |
f()(2); //grabs function g, assings 2 to y, knows z is 1 through closure scope and makes an alert(3) | |
//ANOTHER EXAMPLE | |
function f(y) { | |
var z = 1; | |
function g(y) { | |
alert(y + z); | |
} | |
g(y); | |
} | |
var z=10; | |
f(2); // calls f and alerts 3, inside g JavaScript knows variabe z because it is inside a Closure Scope. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment