DEV Community

Cover image for Understanding "this" in JavaScript and its behavior in various scenarios
Richa
Richa

Posted on

Understanding "this" in JavaScript and its behavior in various scenarios

Have you ever found yourself scratching your head while trying to figure out what this means in JavaScript? If so, you are not alone! Understanding this is similar to learning a new skill: it takes some practice, but once you understand it, everything makes sense.

In this blog, we'll learn what this is, how it works in various scenarios, and even include some examples to help it stick.

Let’s dive in! 🚀

πŸ” What is this?

In JavaScript, the this is a keyword that represents the object to which a function belongs. It allows you to develop reusable and dynamic functions by deciding their value at runtime.

The value of this is totally dependent on how a function is called. This ability gives it flexibility and confusion at times.

πŸ›‘ Key Points about this:

  • this is not a variable; it’s a keyword.
  • You cannot assign a new value to this.
  • Its value is determined at runtime.

πŸ”­ Real-Life Analogy for this
Think of this as a tour guide in a museum.

  • When the guide is in the art museum, they represent the art museum.
  • When they switch to a history museum, they represent the history museum.

Similarly, the value of this depends on the "context" (the function call) and changes accordingly.

πŸ’‘ Understanding this in Different Scenarios

1️⃣ In the Global Context (Default Binding)
When used outside of a function, this refers to the global object.
The value of this in the global context depends on the runtime environment β€” whether you're in a browser or Node.js.

πŸ”“ Without strict mode

  • In the browser, this refers to the window object.
  • In Node.js, this refers to the {} empty object because Node.js wraps your code in a module. Each module has its own scope, and this refers to the module's exports.

πŸ“Œ Example

console.log(this); 
// Output: In browsers, this = window object
// Output: In node.js, this = {}
Enter fullscreen mode Exit fullscreen mode

πŸ”’ With strict mode

  • In the browser, the behavior is still the same because this is fundamentally linked to the global object (window). Even strict mode doesn't change this.
  • In Node.js, this still refers to the module's exports, which remains an empty object ({}).

πŸ“Œ Example

'use strict';
console.log(this); 
// Output: In browsers, this = window object
// Output: In node.js, this = {}
Enter fullscreen mode Exit fullscreen mode

2️⃣ Inside a Regular Function
In a regular function, the value of this is selected by how the function is called.
πŸ”“ Without strict mode

  • In the browser, this refers to the window object.
  • In Node.js, this refers to the global global object.

πŸ“Œ Example

function showThis() {
  console.log(this);
}
showThis();
// Output: In browsers, this = window object
// Output: In node.js, this = global object
Enter fullscreen mode Exit fullscreen mode

πŸ”’ With strict mode
In the browser and Node.js, this is undefined.
πŸ“Œ Example

'use strict'; 
function showThis() {
  console.log(this);
}
showThis();
// Output: undefined
Enter fullscreen mode Exit fullscreen mode

3️⃣ Inside an Object Method (Implicit Binding)
When a function is called as a method of an object, this refers to the object itself.
πŸ“Œ Example

const book = {
    title: 'JavaScript: The Dynamic Language',
    showTitle: function () {
      console.log(this.title);
    },
};

book.showTitle(); // Output: JavaScript: The Dynamic Language
Enter fullscreen mode Exit fullscreen mode

Here, this points to the book object.

4️⃣ With Arrow Functions
Arrow functions do not have their own this. Instead, they inherit this from the surrounding lexical scope (the function or block where they are defined).
πŸ“Œ Example

const techBook = {
  title: 'JavaScript: A Dynamic Language',
  showTitle: function (){
    const arrowFunction = () => {
      console.log(this.title);
    }
    arrowFunction();
  }
}
techBook.showTitle(); // Output: JavaScript: A Dynamic Language
Enter fullscreen mode Exit fullscreen mode

Why? The arrow function does not generate a new this; instead, it uses this of showTitle.

5️⃣ In Constructor Functions (New Binding)
When you use a constructor function with the new keyword, this refers to the newly created object.
πŸ“Œ Example

function Book(title, author){
  this.title = title;
  this.author = author;
}
const myBook = new Book('Javascript', 'TheDevRicha');
console.log(myBook.title, myBook.author); // Output: Javascript TheDevRicha
Enter fullscreen mode Exit fullscreen mode

6️⃣ In Classes
In ES6 classes, this works similarly to constructor functions.
πŸ“Œ Example

class BookInfo{
  constructor(title, author){
    this.title = title;
    this.author = author;
  }
  showDetails(){
    console.log(`${this.title} by ${this.author}`);
  }
}

const bookInfo = new BookInfo('Javascript: Beginner Guide', 'TheDevRicha');
bookInfo.showDetails(); // Output: Javascript: Beginner Guide by TheDevRicha
Enter fullscreen mode Exit fullscreen mode

7️⃣ Using call(), apply(), and bind() (Explicit Binding)
These methods are in-buit functions in JavaScript. You can explicitly set the value of this using these methods.

  1. call(): It invokes the function immediately and allows you to pass arguments one by one.
  2. apply(): Same as call(), but takes arguments as an array.
  3. bind(): It doesn’t invoke the function immediately. Instead, it returns a new function with the this context set to the specified object. You can invoke it later.

πŸ“Œ Example

const member1 = {
  firstName: 'Iron',
  lastName: 'Man'
}

const member2 = {
  firstName: "Jake",
  lastName: "Sparrow",
}

function getMembershipDetail(plan, startYear){
  console.log(`${this.firstName} ${this.lastName} has a ${plan} plan starting in ${startYear}.`);
}

getMembershipDetail.call(member1, 'Gold', 2024); // Output: Iron Man has a Gold plan starting in 2024.
getMembershipDetail.call(member2, 'Silver', 2025) // Output: Jake Sparrow has a Silver plan starting in 2025.

getMembershipDetail.apply(member1, ['Platinum', 2023]); // Output: Iron Man has a Platinum plan starting in 2023.
getMembershipDetail.apply(member2, ['Bronze', 2022]); // Output: Jake Sparrow has a Bronze plan starting in 2022.

const memberShip1 = getMembershipDetail.bind(member1, 'Diamond', 2027);
const memberShip2 = getMembershipDetail.bind(member2, 'Basic', 2028);
memberShip1(); // Output: Iron Man has a Diamond plan starting in 2027.
memberShip2(); // Output: Jake Sparrow has a Basic plan starting in 2028.
Enter fullscreen mode Exit fullscreen mode

8️⃣ In Event Listeners
In regular functions used as event listeners, this refers to the element that received the event.
πŸ“Œ Example

const button = document.querySelector('button');
button.addEventListener('click', function () {
  console.log(this); // `this` refers to the button element
});
Enter fullscreen mode Exit fullscreen mode

πŸͺœ Order of Precedence for this

  1. New binding (Constructor Functions) has the highest priority.
  2. Explicit binding (Using call, apply, or bind) overrides implicit/default binding.
  3. Implicit binding (Object Method) applies when the function is called as a method of an object.
  4. Default binding (Global Context) is the fallback when no other rule applies.

Conclusion

Mastering this in JavaScript is essential for creating clean, context-aware code. While it may appear complex at first, understanding how this behaves in various situations will clarify how it works.

Whether you're working with objects, constructors, or arrow functions, this is an effective tool for connecting data and behavior in your code. With practice and a clear understanding, you'll realize that this isn't as mysterious as it first seems.

Share Your Thoughts

Where have you utilized this in your projects? What issues or benefits did you encounter? Please let me know in the comments section.

Happy Coding!✨

Top comments (6)

Collapse
 
agunechemba profile image
Agunechemba Ekene

Well written mate...

Collapse
 
thedevricha profile image
Richa

Thanks for appreciating!

Collapse
 
frogdoestech profile image
frog

This is cool. And so is this.

Collapse
 
thedevricha profile image
Richa

Thanks for appreciating!
I'm glad you like it.

Collapse
 
anwaar profile image
Anwar

Thank you for this effort.

Collapse
 
thedevricha profile image
Richa

Thanks for appreciating!
I'm glad you like it.