3 ms·
Hm... let me be more explicit: for(var i = 0; i < 10; i++) { setTimeout(function f() { console.log(i); }, 1000); } Here, technically
by tomp 14y ago
Hm... let me be more explicit:
for(var i = 0; i < 10; i++) {
setTimeout(function f() {
console.log(i);
}, 1000);
}
Here, technically speaking, `f` is not a closure, since it doesn't close over any local variables, since there are none (`i` is global).
function a() {
for(var i = 0; i < 10; i++) {
setTimeout(function f() {
console.log(i);
}, 1000);
}
}
Now, `f` is a closure, since it closes over the variable `i`, which is local to `a`. Note, however, that `f` closes over the variable, not over its value. That is the reason that I prefer to call such variables (heap-allocated) boxes, not upvalues.
- mnarayan01 14y agoYou appear to be using a pretty non-standard definition of "closure". Generally speaking (AFAIK), a closure is the function and its referencing environment (with the env potentially simplified to only those variables which occur free in the function). In both your examples `i` occurs free, so it would be part of the closure. Since `i` is global(ish) I guess an interpreter could potentially skip placing it in the closure as an optimization, but I'm not seeing any value to not considering it as part of the closure from a language-understanding standpoint. As an aside...both of your examples have the same effect: logging "10" 10 times. Did you mean something like for(var i = 0; i < 10; i++) { (function (_i) { setTimeout(function f() { console.log(_i); }, 1000); })(i); } instead?
- tomp 14y agoI decided to exclude global variables from my definition of closure to make it perfectly clear that closure, as it exists in JavaScript, LISP, Python and most other functional/modern languages, is different from raw function that can be defined in C, Java, and similar. No, I deliberately chose the "wrong" example, and included a Note, saying that the function doesn't close over the values of its free variables, but rather over the whole variables (in different words, over the references to the values).