More closures examples
What about the
let
keyword?
for (let i = 0; i < 5; i++) {
setTimeout(function(){
console.log("i:" + i);
}, i * 1000);
}
The specs says that let
is bound to each iteration of the for
loop. It's in the spec. let
has block scope, so we could write this as well:
for (var i = 0; i < 5; i++) {
let j = i;
setTimeout(function(){
console.log("j:" + j);
}, i * 1000);
}
Question (from Kyle): is this closure or not?
var foo = (function(){
var o = { bar : "bar" };
return {obj: o };
})();
console.log(foo.obj.bar); // "bar"
I would say not, because we are not returning a function. Or the the IFEE does not run outside it's original scope. Answer: no inner function being exported out, so there's no closure