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?
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.
Dot call operator: If you see a dot call operator e.g
thiswill be pointing to whatever is in the left side of '.' operator
newkeyword: If you are invoking a function with constructor e.g
var c = new Car("Some Car!")then the context within your constructor will be i.e c (in our case)
apply: Finally if you are using
apply()function then the context will be whatever you pass in first argument e.g
car.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
thiswill be pointing to global or window object