Skip to content

Instantly share code, notes, and snippets.

@travishen
Created September 16, 2018 09:59
Show Gist options
  • Save travishen/c456534c8f8620fb1ae818be016c1f5f to your computer and use it in GitHub Desktop.
Save travishen/c456534c8f8620fb1ae818be016c1f5f to your computer and use it in GitHub Desktop.
Classic examples of JavaScript closure
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