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 …


This content originally appeared on DEV Community and was authored by Richa

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 = {}

🔒 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 = {}

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

🔒 With strict mode
In the browser and Node.js, this is undefined.
📌 Example

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

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

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

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

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

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.

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
});

🪜 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!✨


This content originally appeared on DEV Community and was authored by Richa


Print Share Comment Cite Upload Translate Updates
APA

Richa | Sciencx (2025-01-29T04:00:00+00:00) Understanding “this” in JavaScript and its behavior in various scenarios. Retrieved from https://www.scien.cx/2025/01/29/understanding-this-in-javascript-and-its-behavior-in-various-scenarios/

MLA
" » Understanding “this” in JavaScript and its behavior in various scenarios." Richa | Sciencx - Wednesday January 29, 2025, https://www.scien.cx/2025/01/29/understanding-this-in-javascript-and-its-behavior-in-various-scenarios/
HARVARD
Richa | Sciencx Wednesday January 29, 2025 » Understanding “this” in JavaScript and its behavior in various scenarios., viewed ,<https://www.scien.cx/2025/01/29/understanding-this-in-javascript-and-its-behavior-in-various-scenarios/>
VANCOUVER
Richa | Sciencx - » Understanding “this” in JavaScript and its behavior in various scenarios. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/01/29/understanding-this-in-javascript-and-its-behavior-in-various-scenarios/
CHICAGO
" » Understanding “this” in JavaScript and its behavior in various scenarios." Richa | Sciencx - Accessed . https://www.scien.cx/2025/01/29/understanding-this-in-javascript-and-its-behavior-in-various-scenarios/
IEEE
" » Understanding “this” in JavaScript and its behavior in various scenarios." Richa | Sciencx [Online]. Available: https://www.scien.cx/2025/01/29/understanding-this-in-javascript-and-its-behavior-in-various-scenarios/. [Accessed: ]
rf:citation
» Understanding “this” in JavaScript and its behavior in various scenarios | Richa | Sciencx | https://www.scien.cx/2025/01/29/understanding-this-in-javascript-and-its-behavior-in-various-scenarios/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.