34 ms·
You appear to be using a pretty non-standard definition of "closure". Generally speaking (AFAIK), a closure is the function and its referencing environment (wit
by mnarayan01 14y ago
You 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).