this //in JavaScript

a quick look at making JavaScript’s `this` keyword more user friendly

Someone once told me that Java is to JavaScript as Ham is to Hamburger. Well my friends, the this keyword and it’s behavior in both languages certainly lends some merit to that argument. Most modern programming languages like Java have some version of a class and within those classes the this keyword behaves in a fairly predictable way: it will refer to the class instance that you have instantiated. Nothing more, nothing less. Some like it, some don’t, but one thing’s for certain; JavaScript’s this is decidedly different when compared to other modern languages.

What makes it so different is the fact that the value of JavaScript’s this is determined by how the function is called. JavaScript makes this determination at runtime (a process called runtime binding). During this process the compiler does not know about the object through which we are calling the method and so the compiler must determine that at runtime. By that time the object through which our method was called could resolve to the window object in a browser or even the global object in Node.js.

There are a few different ways to handle JavaScript’s funky approach to this. One of the more popular ways is to use ES6’s arrow functions. These functions upon compiling, retain the this value of the enclosing lexical scope. Another strategy is to use the bind() method to explicitly set the value of a method’s this to it’s enclosing lexical scope regardless of how/when it’s called. The last strategy that I’m aware of is simply setting a function as a method of an object — when you do that it’s this is bound to that object.

Long story short, I hope I’ve provided a quick and helpful explanation surrounding the weirdness of this and hopefully these are some useful workarounds that you can easily understand and employ. Cheers!