Understanding JavaScript's 'this' Keyword

Shivam GoswamiShivam Goswami
4 min read

JavaScript is full of quirky behaviors, but one of the trickiest to grasp, especially for beginners, is the this keyword. If you've ever found yourself scratching your head over what this refers to, you're not alone. In this blog, we’ll demystify this using simple language, code examples, and relatable real-world analogies.


What is this in JavaScript?

At its core, this is a reference to the object that is currently executing the code. However, what this refers to depends entirely on how a function is called, not where it is defined.

To really grasp it, let’s look at a simple analogy:

🧍‍♂️ Real-World Analogy: The Delivery Guy

Imagine a delivery guy named JavaScript who has a package (function). The destination of that package (the this context) depends on who calls him.

  • If a restaurant calls him to deliver food, he takes it to the restaurant’s address.

  • If a grocery store calls him, he goes to the grocery store.

Same delivery guy (function), but the destination (this) changes based on the caller.


Different Contexts Where this Works Differently

1. Global Context

In the global execution context (outside of any function), this refers to the global object:

  • window in browsers

  • global in Node.js

console.log(this); // In a browser, it logs: Window {...}

2. Inside a Regular Function

When a function is called in the global context, this defaults to the global object (in non-strict mode).

function greet() {
  console.log(this);
}

greet(); // Logs: Window (in browsers)

📦 Real-world analogy: Think of a public announcement, no matter who reads it, everyone hears the same message.

3. Inside a Method (Object Context)

When a function is a property of an object (i.e., a method), this refers to the object calling the method.

const person = {
  name: 'Shivam',
  greet: function() {
    console.log('Hi, I am ' + this.name);
  }
};

person.greet(); // Logs: Hi, I am Shivam

🍔 Real-world analogy: A waiter (this) takes orders only for the restaurant they work in (object).

4. Arrow Functions

Arrow functions do not have their own this. Instead, they inherit this from their surrounding (lexical) scope.

const team = {
  name: 'Dev Dojo',
  members: ['Alice', 'Bob'],
  intro: function() {
    this.members.forEach(member => {
      console.log(`${member} is part of ${this.name}`);
    });
  }
};

team.intro(); // Works as expected

⚠️ If you used a regular function inside forEach, this.name would be undefined!

Real-world analogy: Arrow functions act like loyal sidekicks, they follow the lead of their boss (outer function).

5. Constructor Functions and Classes

When you use new, this refers to the newly created object.

function Car(model) {
  this.model = model;
}

const myCar = new Car('Tesla');
console.log(myCar.model); // Tesla

Real-world analogy: Like a factory producing a new car, this refers to the current car being built.

6. call(), apply(), and bind()

These methods allow us to explicitly set the value of this.

function sayHello() {
  console.log(`Hello, I am ${this.name}`);
}

const user = { name: 'Shivam' };
sayHello.call(user); // Hello, I am Shivam

Analogy: Think of it as giving a mic to someone specific and telling them to say the lines. You're controlling who speaks.

7. Event Handlers in the DOM

When a function is used as an event handler, this refers to the element that received the event.

document.getElementById('btn').addEventListener('click', function() {
  console.log(this); // Refers to the clicked button
});

🖱️ Real-world analogy: Whoever clicks the button gets to talk (i.e., becomes this).


🔁 Summary Table

ContextWhat this refers to
Global ScopeGlobal object (window or global)
Regular FunctionGlobal object (non-strict mode)
Method in ObjectThe object itself
Arrow FunctionLexical (outer) context
Constructor or ClassNewly created instance
call/apply/bindExplicitly set object
DOM Event HandlerThe HTML element that received event

🛠️ Best Practices to Avoid Confusion

  1. Prefer arrow functions when working with callbacks or inside methods that need this from the outer context.

  2. Use bind() to fix this in class methods or callbacks.

  3. Don’t overuse this, sometimes simpler code avoids it entirely.


🧩 Conclusion

Understanding how this works is a major step toward mastering JavaScript. While it may seem confusing at first, thinking in terms of who calls the function helps make things clearer. The more you practice writing and debugging code involving this, the more natural it becomes.

Next time you're stuck wondering "what is this?", just remember: this is not what you write—it’s how you call it.

Stay curious, keep building, and get ready—React is just around the corner!

0
Subscribe to my newsletter

Read articles from Shivam Goswami directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shivam Goswami
Shivam Goswami

A passionate tech advocate with a strong foundation in Web Development and a deep interest in the evolving Web 3 space. As a Developer Relations (DevRel) professional, I focus on bridging the gap between developers and products, ensuring they have the right tools and support to thrive.