Created
September 16, 2018 09:59
-
-
Save travishen/c456534c8f8620fb1ae818be016c1f5f to your computer and use it in GitHub Desktop.
Classic examples of JavaScript closure
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
function buildFunctions() { | |
var arr = []; | |
for(var i=0; i<3; i++) { | |
// add three function to arr | |
arr.push( | |
function() { | |
console.log(i); | |
} | |
) | |
} | |
return arr; | |
} | |
var func_arr = buildFunctions(); | |
func_arr[0](); // 3 | |
func_arr[1](); // 3 | |
func_arr[2](); // 3 | |
function buildFunctions2() { | |
var arr = []; | |
for(var i=0; i<3; i++) { | |
// add three function to arr, use iife to create | |
// three more execution context and store i's value | |
arr.push( | |
(function(j){ | |
return function() { | |
console.log(j); | |
} | |
}(i)) | |
) | |
} | |
return arr; | |
} | |
var func_arr2 = buildFunctions2(); | |
func_arr2[0](); // 0 | |
func_arr2[1](); // 1 | |
func_arr2[2](); // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment