Here's the code:
for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i); //prints 9 10 times
console.log(this.i); //prints 0, 1, 2...9
}.bind({i:i}), i * 1000);
}
Why do i
and this.i
refer to different things?
Contrast this to a bit of code executed on the global scope:
var x = 5;
console.log(x);
console.log(this.x);//both will print 5
Here the scope was global, and so was the context. A variable declaration set a property of the same name on the global context. On the other hand, within a function scope, this doesn't happen.
var a = function() {
var x = 5;
console.log(x); //5
console.log(this.x); //undefined
console.log(i); //undefined
console.log(this.i); //10
}.bind({i: 10});
a();
Even if we pass the global context into the local scope, declaring a variable within the function doesn't set it as a property of the global context.
var a = function() {
var x = 5;
console.log(x); //5
console.log(this.x); //undefined
}.bind(window);
a();
console.log(x); //undefined
console.log(this.x); //undefined
What I'm trying to say is this: in the global scope, a variable declaration modifies the global context. But in a function scope, a variable declaration doesn't modify the function's context, no matter what the context is. Why?