Function declaration in EcmaScript 6 are now block-scoped, just like let
declarations (with the difference with let
that the variable is declared in the outer global/functionnal scope).
Your code is globally equivalent to
for (var i = 1; i <= 2; i++) {
let timer = function() {
console.log("in timer");
console.log(timer.i);
}
timer.i = i;
setTimeout(timer, 1000);
}
This means you have different timer
values.
Note that if you had used var
instead of let
and instead of a function declaration, you would have got twice the same log.
A good read: http://2ality.com/2015/02/es6-scoping.html
Please note that adding properties to a function isn't really a good practice. You should use scope variables for this, for example:
for (var i = 1; i <= 2; i++) {
let timer_i = i;
setTimeout(function timer(){
console.log("in timer");
console.log(timer_i);
}, 1000);
}
which in this simple case could be just written as
for (let i = 1; i <= 2; i++) {
setTimeout(function timer(){
console.log("in timer");
console.log(i);
}, 1000);
}