loading...

Simple Rules to Master 'this' Context

dotnetdreamer profile image Idrees Khan ・2 min read

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?

Alt Text

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?

Alt Text

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?

Alt Text

In this case it will point to 'c' object. Now if I change this abit more guess what it is pointing to?

Alt Text

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

  1. 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
  2. new keyword: 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)
  3. call or apply: Finally if you are using call() or 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
  4. 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

Posted on May 29 by:

dotnetdreamer profile

Idrees Khan

@dotnetdreamer

Full Stack Developer | Building Web/Mobile Apps | Working With Angular, Node.js, NativeScript, .Net Core

Discussion

markdown guide
 

Hi Idress! The rules are in the wrong order, actually it should be:

  1. new keyword
  2. bind (hard binding) // call or apply (explicit binding)
  3. dot call operator (implicit binding)
  4. global or undefined (default object)
 

Thanks for the correction 😅

 

Hey nice - I would just point out you've missed out .bind() as a method of fixing this. 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 😅