Skip to content

Instantly share code, notes, and snippets.

@ehernandez-xk
Created November 6, 2015 12:26
Show Gist options
  • Save ehernandez-xk/955ac6bf3d285c7bfb5e to your computer and use it in GitHub Desktop.
Save ehernandez-xk/955ac6bf3d285c7bfb5e to your computer and use it in GitHub Desktop.
javascript - closures
// Closures
// What is the especting output
function builFunctions () {
var arr = [];
for (var i = 0; i < 3; i++) {
arr.push(
function () {
console.log(i);
}
)
}
return arr;
}
var fs = builFunctions();
console.log(fs[0]);
fs[0](); // invoking function
fs[1]();
fs[2]();
/*command line output
function() {
console.log(i);
}
3
3
3
*/
// Explanation: The value of "i" when we hit the return is "3" the outer environment reference saves the i=3,
// The value of the variables when the Execution context is finished.
// For example each funciton are a children and respond how old are their father.
console.log("another way --------------");
function builFunctions2 () {
"use strict";
var arr = [];
for (var i = 0; i < 3; i++) {
let j = i;
arr.push(
function () {
console.log(j);
}
)
}
return arr;
}
var fs2 = builFunctions2();
console.log(fs[0]);
fs2[0](); // invoking function
fs2[1]();
fs2[2]();
/*command line output
function() {
console.log(i);
}
0
1
2
*/
console.log("another way --------------");
function builFunctions3 () {
var arr = [];
for (var i = 0; i < 3; i++) {
arr.push(
(function(j){
return function() {
console.log(j);
}
}(i))
)
}
return arr;
}
var fs3 = builFunctions3();
console.log(fs3[0]);
fs3[0](); // invoking function
fs3[1]();
fs3[2]();
/*command line output
function() {
console.log(i);
}
0
1
2
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment