0

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)

ArunM
  • 2,274
  • 3
  • 25
  • 47
  • Look at what object the function is called on, if any. Here `foo();` there is none, so `this` inside is the global object or `undefined`. Otherwise `o2.foo()` you can see that it's called as a part of an object: `o2`, so `o2` is what `this` refers to inside the function. – CertainPerformance Nov 12 '21 at 00:04
  • no 2 should print `undefined` twice. Once inside of `foo` since `bar` isn't defined anywhere, and next in the last line where it outputs the return value of `foo` which is also undefined – Garr Godfrey Nov 12 '21 at 00:22

0 Answers0