avatarMax N

Summary

The 'this' keyword in JavaScript is context-dependent, referring to the global object, an object's method, a new object in a constructor, or adopting the surrounding context in the case of arrow functions.

Abstract

Understanding the 'this' keyword in JavaScript is crucial for developers, as it behaves differently based on the execution context, which can be the global context, a function context, a method context, or a constructor context. The article aims to demystify 'this' by providing examples and rules of thumb for each context, emphasizing that 'this' refers to the object that the function is a property of, defaults to the global object in regular functions, adopts the surrounding context in arrow functions, and binds to a new object when using the 'new' keyword. A practical example of a user dashboard application is used to illustrate these concepts in action. Mastering 'this' is challenging but essential for JavaScript proficiency, and developers are encouraged to take their time and consider the execution context carefully.

Opinions

  • The author suggests that understanding 'this' is key to mastering JavaScript, implying its importance in the language.
  • The article posits that 'this' is notorious for confusing developers, indicating a common struggle among JavaScript learners.
  • The use of clear examples and rules of thumb is intended to provide clarity and aid in learning the concept.
  • The author emphasizes the value of practice and patience when dealing with the 'this' keyword, suggesting that it is a skill that can be developed over time.
  • By encouraging developers to consider the execution context, the author advocates for a thoughtful and deliberate approach to using 'this'.

The Confusing ‘this’ Keyword in JavaScript: A Simple Explanation

Demystifying How ‘this’ Works in Different Contexts

Photo by Jamie Templeton on Unsplash

The ‘this’ keyword in JavaScript is notorious for confusing developers. Unlike most other programming languages, ‘this’ in JavaScript behaves very differently depending on the execution context. Understanding how ‘this’ works is key to mastering JavaScript.

In this article, we’ll walk through ‘this’ in various contexts and show clear examples of what it refers to in each case. Read on to finally gain clarity on the confusing JavaScript ‘this’!

‘this’ Refers to Different Things Based on Context

The key thing to know about ‘this’ in JavaScript is that what it points to depends entirely on how the function is called. Here are the main contexts that impact what ‘this’ will be:

1. Global Context — In the global execution context (outside any functions), ‘this’ refers to the global object, which is the window object in the browser or the global object in Node.js.

For example:

console.log(this); // window object (in browsers) or global object (in Node)

2. Function Context — Inside a regular function call, ‘this’ refers to the global object (window or global).

For example:

function myFunc() {
  console.log(this); // window or global
}

myFunc();

3. Method Context — When a function is called as a method of an object, ‘this’ refers to that parent object.

For example:

const myObject = {
  myMethod: function() {
    console.log(this); // Logs myObject
  }  
}

myObject.myMethod();

4. Constructor Context — When JavaScript’s ‘new’ keyword calls a function, a new object is created and ‘this’ gets bound to it.

For example:

function Car(make, model) {
  // The newly created object gets bound to this
  this.make = make;  
  this.model = model;  
}

const myCar = new Car('Toyota', 'Camry'); 
console.log(myCar.make); // 'Toyota'

That covers the main contexts that impact what ‘this’ refers to!

Rules of Thumb for Understanding ‘this’

While the context largely determines what ‘this’ points to, here are some useful rules of thumb:

1. ‘this’ refers to the object that the function is a property of. So myObject.myMethod’s ‘this’ is myObject.

2. Regular functions not attached to objects will have the global object (window, global) as ‘this’.

3. Arrow functions adopt the ‘this’ value of their surrounding functional context.

4. Whenever you instantiate an object using ‘new’, the new object gets bound as ‘this’.

Keep these rules handy as you work with ‘this’. They explain most cases!

A Practical Example — User Dashboard

Let’s walk through a practical example of ‘this’ while building out a user dashboard application.

We’ll start by creating a User constructor function to represent each user:

function User(name, email) {
  // The new user object is created and bound to this
  this.name = name;
  this.email = email;  
}

const user1 = new User('Michelle', '[email protected]');

Then we can build a Dashboard class to display user data:

function Dashboard() {
  const displayedUser = null;
  
  this.display = function(user) {
    displayedUser = user; 
    
    this.showInfo = function() {
      // Here this still refers to the Dashboard instance  
      console.log(`Name: ${displayedUser.name}, Email: ${displayedUser.email}`);
    };
  };
}

const myDashboard = new Dashboard();
myDashboard.display(user1);
myDashboard.showInfo(); // Shows user1 info

This demonstrates ‘this’ binding to the new user instance, new dashboard instance, and dashboard method contexts.

The key is recognizing how ‘this’ changes depending on where functions are called!

Mastering ‘this’ Takes Time — But You Can Do It!

JavaScript’s ‘this’ keyword continues to trip up both beginner and experienced JS developers. But now you have a simple mental model for understanding how ‘this’ changes based on context.

Refer back to the rules of thumb and examples above whenever you run into issues with ‘this’. With practice, you’ll gain confidence using ‘this’ correctly as you build projects.

The key is not rushing — take time to ask yourself “what is the execution context here?” whenever ‘this’ is involved. Slowing down to understand the current context is the best approach.

With context top of mind, you’ll join the ranks of developers who have mastered the tricky ‘this’ keyword!

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

This
JavaScript
Javascript Tips
Javascript Development
Programming
Recommended from ReadMedium