In following example I have a couple of surprises:
I am sad, people not even reading question properly before voting it down. JSFiddle wraps variables to set them local. Please, dont show it as a proof in this case! --- And, also someone who was extra clever removed my code and wrapped it in fiddle to show his Great Stupidity to next level!
Snippet:
this.a = 100;
var a = 200;
function b() {
this.a = 300;
setTimeout(function() {
console.log(this.a)
}, 0);
}
b();
console.log("Hello");
console.log(a);
Result:
Query:
When setTimeout is 0, the first log must be 300. Why do I see Hello printed before? (As function b is executed before "console.log(Hello)".
The 3rd log must have the value "200", as this.a in both lines refers to window.a as this refers to window object in both locations. variable a still hods value as 200.
While chrome shows Hello, 300, 300 Fiddle shows Hello, 200, 300
Any explanations for these 2 phenomenons?
Note: JSfiddle wraps the code in function to set them as local variables, so dont consider it for the current example. Try out in Chrome!