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.x
inside the function ofsetTimeout
, thus it is printing4
, however, if you do not usethis.x
it shall print1
to 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 scope
of the function. But refer toglobal scope
because it’s the invocation context of the function.