Example No:1
function foo() {
console.log(this.bar)
}
var bar = "bar1"
foo();
Example No:2
function foo() {
console.log(this.bar)
}
var o2 = {foo:foo}
console.log(o2.foo())
Example No:1 will print bar1
where as example no:2 will print undefined
. It seems pretty counter intuitive to me that in the first scenario javascript will look at the global scope where as in the second scenario it will not use scoping rules.
Why does the language work this way or is this some arbitrary rule that I need to remember(whenever there is an object involved javascript engine will not consider scoping rules)