When I was learning JS for the first time, the first difficult thing to grasp was this. Yes! you won't believe it but that is what I felt.
So in this article I will do my best to explain 3 basic rules that I learned at that time which will make you master the this
context in browser environment.
A quick side note before we proceed, many issues of this context are actually solved in ES6+ standard and so I will be using ES5 to demonstrate it.
Consider following example and guess What's this
pointing too?
Well to car
. If you have guessed it right then you are at a good place. Let me change this abit and guess what is this
pointing to?
Well to Window object. Yes! you heared it right. You didn't expect it to see but trust me it does!
Now consider following example and guess what is this
pointing to?
In this case it will point to 'c' object. Now if I change this abit more guess what it is pointing to?
It is pointing to Window object! Isn't this weird? it is, specially if you have came to JS from other languages such as C#.
This is getting boring let me break it down into following rules.
Rule of Thumb for this
-
Dot call operator: If you see a dot call operator e.g
car.beepBeep()
,this
will be pointing to whatever is in the left side of '.' operator -
new
keyword: If you are invoking a function with constructor e.gvar c = new Car("Some Car!")
then the context within your constructor will be i.e c (in our case) -
call
orapply
: Finally if you are usingcall()
orapply()
function then the context will be whatever you pass in first argument e.gcar.beeBeep.call(otherCar)
. In this case the context will be otherCar - In JS functions don't know where they live, they only know how they are called. So if none of the above rules apply then
this
will be pointing to global or window object
Top comments (4)
Hi Idress! The rules are in the wrong order, actually it should be:
Thanks for the correction π
Hey nice - I would just point out you've missed out
.bind()
as a method of fixingthis
. Especially important if you forward functions to other places - or use event handlers etc.To be honest, I never used but glad that you have pointed out π