I know it is 2018 already, but this keyword still manifests to be one of the most confusing parts of JavaScript. And it haunts me occasionally with some weird and unexpected bugs. So, I figured there is still some value to dive deep into how this works since it’s vital and is the foundation of more advanced concepts such as prototype chain and closure.

First, two basic important rules:

  • JavaScript has Lexical Scoping with function scope. This means that the variable scope is determined by its location of the code. We can infer the code by just reading the code instead of going through compilation, as opposed to Dynamic Scoping.
  • Although we can’t change JavaScript’s essence of lexical scoping, we can control the context when a function is called. Context is an activation record that is created automatically when a function gets called. It carries information about the function such as where is the call-back, how it is called, etc. One of the attributes of this record is this, which points to the object during its execution context. (See details in the Implicitly rule.)

Overall, there are four rules of how this works:  globally, implicitly, explicitly and constructively with the new keyword.

Globally

When this is outside of a declared object, this refers to the global object, which is a window object in browsers and a global object in the Node environment.

Although it looks like something we may want to use, this is actually a bad design, which can bring many issues if the developer accidentally misuses this and puts some variable on the global that everyone has access to, while meaning to keep the variable to a certain scope. For example:

Generally, the best practice is to declare all the global variables at the top of the code and set/update them in the functions at a later time. Declaring a global variable in a function scope is neither clean, nor easy to understand.

Thankfully, strict mode is introduced by ES5 to help us write better code. With strict mode being turned on by adding 'use strict' to the file, it is impossible to accidentally create global variables. When we are not inside a declared object, this is “undefined” instead of global scope.

Implicitly

This rule means:

  1. When function is called using object.foo()this in the function foo refers to the calling object (the context).

For example:

In this example, although person.sayHi and sayHi point to the exactly same function, the results are different because the contexts are different. In the first example, the calling object is the person object, while in the second example the calling object is the global object. And in this case, the window object. That is why each function grabs the corresponding name variable of the context.

  1. When this is inside of a declared object, the value of this will be the closest parent object.

Things can get trickier in nested objects, but looking for the closest parent object can always help figure out the correct scope. For instance:

In this example, the cat object is nested inside the person object. When calling sayAge() in catthis is indeed inside a declared object, and the closest parent object is cat.Since cat doesn’t have an age variable in the object scope, it is returning undefined for this.age.

What if we want to borrow the implementation of the sayAge function but only want to change the value of this to person? That way our code can be drier. JavaScript offered three methods that enable us to change the value of this explicitly.

Explicitly

These three methods are call()apply() and bind(). These are super powerful methods. which make JavaScript calls very flexible, and each has its own best use case. For what it’s worth, these methods can only be used on functions.

Method Syntax Invoked Immediately?
call call(thisArg, …) Yes
apply apply(thisArg, […]) Yes
bind bind(thisArg, …) No, returns func definition
  • call() and apply() are very similar and they are very common in JavaScript for borrowing methods by changing the value of this, except a syntax difference, call() method, takes all the parameters separated by comma while apply() takes an array of parameters, making it suitable for variadic functions.
  • call and apply are invoked immediately with setting this, while bind just returns the function definition. This makes it great for function currying (We don’t want to invoke the function right away because not all arguments are ready yet.) or async method.
  • bind takes arguments separated by commas just like call.
  • ES6 introduced Arrow Functionsin which scopes are set lexically. It always refers to its execution context, and is no longer affected by callapply and bind, so thisArg can be omitted.

Example of call and apply:

How bind can be used with partial function application:

bind is also commonly used in async methods where the context of this can be a little confusing:

In this example, you may say, “Since this is inside a declared object, this refers to the closest object, which is the baz object in this case.” However, the callback function within the setTimeOut is not called instantly, but rather later. And by the time it is called, the context isn’t the baz object anymore. It’s the global object – window. In order to fix this, we can explicitly bind the this of the callback to baz object, which is what this refers when sayHey is invoked. So, this solution can be:

The first parameter this in the bind method refers to the baz object when we declare the setTimeOut, thus setting the context of this in the callback to also be baz object.

Constructively

This rule is pretty straight-forward: When using the new operator, this refers to the new object itself. For instance, when declaring function object Person:

Reference and Extension Reading

What is the Execution Context & Stack in JavaScript?

What You Should Already Know about JavaScript Scope

You Dont Know JS

MDN site

 

Leave a Comment