Here is the code:
for (var i = 0; i < 10; i++) { setTimeout(function() { console.log(i);
Why do i and this.i refer to different things?
Contrast this with a bit of code running in a global scope:
var x = 5; console.log(x); console.log(this.x);
Here the scale was global, and the context too. A variable declaration sets a property with the same name in a global context. On the other hand, this does not occur within the scope of the function.
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 to a local scope, declaring a variable inside a function does not 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
I'm trying to say the following: in a global scope, declaring a variable changes the global context . But in the area of functions, the declaration does not change the context of the function , regardless of the context. Why?
source share