Please provide an explanation why the output will be 4. I am trying to understand that the output is 4 but cannot find the reason why is it not 3.
var x=4,
obj={
x: 3,
bar:function(){
var x = 2;
setTimeout(function(){
var x=1;
console.log(this.x);
},1000);
}
}
obj.bar();
You are using
this.xinside the function ofsetTimeout, thus it is printing4, however, if you do not usethis.xit shall print1to the console. You must remember that the**this**keyword behaves differently in JavaScript compared to other languages. In JavaScript, the value of**this**does not refer to the function in which it is used or its scope but is determined mostly by the invocation context of function(context.function())and where it is called.As you see in the above example
**this**in setTimeout function does not refer to thelexical scopeof the function. But refer toglobal scopebecause it’s the invocation context of the function.