Back to Blog Listing

Demystifying the 'this' Keyword in JavaScript

The behavior of the this keyword is one of the most common friction points in JavaScript. In class-based languages, this refers to the class instance. In JavaScript, this depends on how a function is invoked.

The Four Binding Rules

  1. Default Binding: In standalone function calls, this refers to the global object (window in browsers) or undefined in strict mode.
  2. Implicit Binding: When a function is called as a method on an object, this points to the object preceding the dot.
  3. Explicit Binding: You can force a function to use a specific object as its context using call, apply, or bind.
  4. New Binding: When a function is called with the new keyword, this refers to the newly created instance.

Arrow Functions and Lexical Context

Arrow functions do not have their own this context. They capture the this value of the enclosing execution context, making them ideal for callbacks inside methods:

const group = {
  title: "My Group",
  members: ["Alice", "Bob"],
  showMembers() {
    this.members.forEach(member => {
      console.log(this.title + ": " + member); // works because of arrow fn lexical bind
    });
  }
};
group.showMembers();
💻

Try this code in our online compiler!

Don't just read about it. Write, run, and experiment with these JavaScript concepts instantly on our online workspace with autocomplete suggestions.

Share this tutorial:

CodeCompile