Last active
December 7, 2015 12:51
-
-
Save jsec516/40cd2e39b69a2f71de83 to your computer and use it in GitHub Desktop.
Closure behavior experimented
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 foo(){ | |
var a = 2; | |
function bar(){ | |
console.log( a ); | |
} | |
bar(); // 2 not-closure, regular lexical scope actually | |
} | |
foo(); | |
/*======= closure ==============*/ | |
function foo(){ | |
var a = 2; | |
function bar(){ | |
console.log(a); | |
} | |
return bar; | |
} | |
var baz = foo(); | |
baz(); // 2 -- closure observed here | |
/*============== weird piece of code ====================*/ | |
for (var i=1; i<=5; i++){ | |
(function(){ | |
setTimeout(function time(){ | |
console.log(i); | |
}, i*1000); | |
})(); | |
} | |
// result is 6 - for 5 times but we expected 1,2,3,4,5 | |
for (var i=1; i<=5; i++){ | |
(function(i){ | |
setTimeout(function time(){ | |
console.log(i); | |
}, i*1000); | |
})(i); | |
} | |
// result is 1,2,3,4,5 because we created scope variable j to remember value of i in the scope of closure | |
for (var i=1; i<=5; i++){ | |
let j = i; | |
setTimeout(function time(){ | |
console.log(j); | |
}, j*1000); | |
} | |
// works as above because let defines for each loop scope. | |
for (let i=1; i<=5; i++){ | |
setTimeout(function time(){ | |
console.log(i); | |
}, i*1000); | |
} | |
// works as above because let defines for each loop scope. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment