Understanding the this Keyword in JavaScript

Published: (April 4, 2026 at 01:47 AM EDT)
3 min read
Source: Dev.to

Source: Dev.to

Introduction

JavaScript has a special keyword called this that often confuses beginners.
The key idea: this refers to the object that is “calling” the function.

this in the Global Context

In the global scope:

// In a browser → points to `window` object
// In Node.js → points to `global` object

Visual:
Global scope → this = window (browser) / global (Node)

this Inside Objects

When a function is called as a method of an object, this points to that object.

const user = {
  name: "Rahul",
  greet() {
    console.log(`Hello, ${this.name}`);
  }
};

user.greet(); // Hello, Rahul
  • this refers to user because user is the caller of greet().

Visual Representation

user → greet() → this = user

this Inside Functions

In a regular function:

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

sayHello(); // Global object (window/global) or undefined in strict mode
  • Here, this does not point to the function itself; it depends on how the function is called.

Changing Context: call, apply, bind

You can manually set this using the following methods:

const user = { name: "Rahul" };

function greet(age) {
  console.log(`${this.name} is ${age} years old`);
}

greet.call(user, 22);          // Rahul is 22
greet.apply(user, [22]);       // Rahul is 22

const boundGreet = greet.bind(user);
boundGreet(22);                // Rahul is 22
  • call → invoke immediately, arguments passed separately
  • apply → invoke immediately, arguments passed as an array
  • bind → returns a new function with this bound to the specified object

this in Arrow Functions

Arrow functions do not have their own this; they inherit it from the surrounding (lexical) scope.

const user = {
  name: "Rahul",
  greet: () => {
    console.log(this.name);
  }
};

user.greet(); // undefined (inherits `this` from global scope, not `user`)

Key Takeaways

  • this refers to the caller of the function, not the function itself.
  • Global context → points to window (browser) or global (Node).
  • Object method → points to the object calling the method.
  • Regular function → global object (or undefined in strict mode).
  • Arrow functions → lexically inherit this from the surrounding scope.

Context Cheat Sheet

Contextthis Points To
Globalwindow / global
Object methodObject calling the method
Regular functionGlobal object (or undefined in strict mode)
Arrow functionSurrounding lexical scope
call/apply/bindExplicitly set object
0 views
Back to Blog

Related posts

Read more »

Understanding Functions in JavaScript

What is a Function? A function is a block of code designed to perform a specific task. Instead of writing the same code repeatedly, you can write it once insid...

Execution Context

Bayangkan Execution Context seperti sebuah dapur. Sebelum kamu memulai memasak mengeksekusi kode, kamu perlu ruang kerja, peralatan variabel, dan resep function...