JavaScript: what is ‘this’?

Volcan de Agua as seen from neighboring Pacaya. Learning can feel like scaling a mountain sometimes.

As I’m learning more and more about JavaScript, it seems like I get tripped up by the keyword this fairly often, so I’m writing my first post to help myself and others understand how to determine it’s context!

The keyword ‘this’ is a reserved keyword that is determined by the execution context (more colloquially, the function that uses it). If you can master the four rules of ‘this’, you shouldn’t have an issue determining what ‘this’ is referring to.

the four rules of ‘this’:

  • global context — when ‘this’ is not inside of a declared object, it is attached to the global object (window). This also applies to using this in a function that is outside of an object. Note that ‘this’ will be undefined if you are using strict mode (“use strict”).
  • object/implicit — when ‘this’ is used in a function that is inside of a declared object, the value of the keyword ‘this’ will be the closest parent object.
  • explicit — you can use the methods .call(), .apply(), and .bind() on your function to change what the keyword ‘this’ is referring to. Each of these methods’ first argument defines the new context of ‘this’, then additional arguments. The methods .call() and .apply are similar, except apply accepts an array of arguments after the ‘this’ argument rather than a comma delimited list; both are also executed immediately. 
    .bind() is almost identical to .call(), but is different in that it returns a function definition with the keyword ‘this’ set to the first argument, which allows you to save functions for later and sets the stage for awesome techniques like currying.
  • new — Whenever a constructor function is used, this refers to the specific instance of the object that is created and returned by the constructor function.

I hope this post helps you understand the different instances of the keyword this. I will try and add to it as I learn more. Thanks for reading!