Initial question
The below code should return 1
,3
since x: 1
is just present above return
statement - however, it's returning 3
,1
. Why is this? Will it be same result when we use let
and/or const
.
It would be great if you guys explain, so that I can improve my fundamentals. Below is my code:
var x = 3;
var foo = {
x: 2,
baz: {
x: 1,
bar: function() {
console.log("this--->", this);
return this.x;
}
}
}
var go = foo.baz.bar;
alert(go());
alert(foo.baz.bar());
Update 1:
In the first case bar
is considered as a closure which has access to the variables outside and prints 3
:
bar: function() {
console.log("this--->", this);
return this.x;
}