Why "this" gives Type Error , kindly guide

Why "this" gives Type Error , kindly guide
0.0 0

#1

So, again i thought i knew “this” pretty well in JS , till i came across a simple example and it gives 2 different errors …

"use strict"
function foo() {
console.log(this.bar);
}

foo()
 VM247:3 Uncaught TypeError: Cannot read property 'bar' of undefined
    at foo (<anonymous>:3:18)
    at <anonymous>:1:1
foo @ VM247:3
(anonymous) @ VM257:1

Here as you can see i get an type error as there is no bar in global and undefined.bar gives the typeerror which basically says i am trying to do something that is not possible…

However here –

"use strict"
function foo() {
console.log(bar);
}

foo()
VM264:3 Uncaught ReferenceError: bar is not defined
    at foo (<anonymous>:3:13)
    at <anonymous>:1:1

Now i get reference error as it is not able to find bar now why i get Reference Error here and type error earlier with this , can any one please guide … Thanks


#2

In the second example, where have you declared bar in your code? If you don’t declare it in either the global scope or inside foo, then it is not defined when you reference it.


#3

@randelldawson - yes but why i get a type error when i decide to use the this keyword, what impact does using “this” keyword have is what i want guidance on , thanks …


#4

I thought your main question was about the second example, where you are not using the this keyword. So you do understand why you are getting a reference error in the second example?

Regarding your above statement about the first example, you are getting a type error because in strict mode, the value of this is the same value it had before entering the function. Since this was not defined, it has a value of undefined. Since undefined does not have properties, this.bar creates a type error.

In non-strict mode, the value of this inside the function would be the window in a browser, because this was not set by the call to the function. So this.bar is does not result in an error, because this refers to the window and since there is no bar property on the window, it just returns undefined.