javascript this

Javascript ‘This’ — The Pointer To All Good Things

By default, your Javascript statements execute in the contexts their positions dictate whether the context is inside a class, in the global scope, or inside a specific block. In all these cases, Javascript uses the reserved keyword this to identify the execution context.

Since the Javascript standard now allows for object-oriented classes, the this keyword can now apply to execution context inside classes. Modern Javascript also adds a few new considerations to this contexts with recent constructs like arrow functions.

This article describes how the Javascript this keyword influences code execution and how to use it in modern Javascript.

What is Javascript ‘This’?

The reserved Javascript keyword this describes the current execution context of Javascript functions, classes, and statements. Execution contexts are usually determined at runtime, although there are instances where setting the execution context is necessary. Please see Udacity’s article about Javascript call() and its related functions for more details about these cases.

Javascript This In Global Context

It is rarely useful to explicitly specify this in the global context, since the global context is where the Javascript execution environment resides. If you ever must explicitly refer to the global context (inside a callback function, for example), use the global property globalThis.

Prior to globalThis, there was not a consistent cross-browser way to access the global context in Javascript, and polyfills (Javascript code that imitates the action of newer Javascript features while using older Javascript syntax) exist for those older browsers. All modern browsers — released in 2019 or later — should support globalThis.

In Function Context

The value of this may change depending on whether you run your Javascript code in strict mode. Strict mode makes Javascript adhere to more stringent execution conventions to prevent common errors caused by less robust programming. For example, within a function, the value of this equals the global context in strict mode, but is undefined in strict mode.

// Non-strict mode
function example1a() {
    console.log(this);  // globalThis
}

// Strict mode
"use strict";
function example1b() {
    console.log(this);  // undefined
}

Some older browsers incorrectly returned the Window object as the global context from a function in non-strict mode, rather than the proper globalThis global property, but it is rare to encounter these browsers today. To ensure consistent values of this across browsers, always use strict mode in production code.

In Event Listeners and Handlers

Inside a DOM event handler, the context of this is usually the element the listener is placed on. Browsers do not always follow this convention, so the Javascript bind() method may be necessary to clarify context. Both separate and inline event listeners handle context this way. (Read more about bind() and apply() near the bottom of our blog post on call().)

This example of event listeners activating on a button click shows how functions in the global context must have the globalThis context bound to them to prevent undefined values.

"use strict";
function example2() {
    console.log(this);
}

button.addActionListener("click", example2);
button.addActionListener("click", example2.bind(globalThis));

Javascript ‘This’ in ES2015 and Later

Javascript ES2015, also known as Javascript ES6, introduced new execution contexts for Javascript code and new uses for the this keyword: classes and arrow functions.

Classes

The introduction of classes into Javascript created a new form of this context that encapsulates properties and methods together. In addition, everything inside a Javascript class is implicitly run in strict mode, so there is much less contextual ambiguity possible than in structures outside of classes.

Methods inside classes must be explicitly bound to the class inside the class constructor to make sure that their context will always be inside the class. If you do not bind() class methods to the class constructor, it is possible to use the wrong context inside those methods unintentionally. For example, you could overwrite a class property or bind() a method to the wrong context by mistake.

This example shows how to bind() class methods to a class constructor.

class example3 {
    myPublic;
    constructor() {
        this.myPublic = true;
        this.myMethod = this.myMethod.bind(this);
    }
    myMethod() {
        return ${this.myPublic};
    }
}

A best practice to maintain robust context in classes is to explicitly bind() all class properties and class methods to the constructor.

Arrow Functions

Arrow functions are a simplified way to write function definitions. They are useful for short functions that you must use often. This example shows the difference between a traditional function definition and an equivalent definition using an arrow function.

// Traditional definition
function example4a() {
    return "I love purple!";
}

// Definition by arrow function
let example4b = () => "I love purple!";

Arrow functions do not have a context of their own, so a call to this in an arrow function returns the context of the structure that encloses the arrow function. Therefore, an arrow function in the global context will have a context equivalent to globalThis.

Avoid using arrow functions in non-strict mode, especially if an arrow function is wrapped inside another function. An arrow function wrapped inside a global function will have the same problems with undefined context as the function itself.

// Non-strict mode
function example5a() {
    console.log(this);  // ==> globalThis
    let context = (() => this);
    return context;     // ==> globalThis (also)
}

// Strict mode
"use strict";
function example5b() {
    console.log(this);  // ==> undefined
    let context = (() => this);
    return context;     // => undefined (watch out!)
}

Conclusion

The Javascript this keyword identifies the current execution context of Javascript code. Some strategies for execution contexts changed after the introduction of Javascript ES2015, but many have remained the same.

The this keyword is applicable in both object-oriented and functional programming, depending on a developer’s needs. When explicitly changing the execution context of code by changing this, be as clear and explicit as possible in both code and comments.

Start Learning

To learn more about Javascript, check out other Javascript blog posts and enroll in our Javascript Nanodegree programs, including Intermediate Javascript.