Skip to main content

Command Palette

Search for a command to run...

Understanding the this Keyword in JavaScript

Published
2 min read
A
my work defines me

The this keyword is often considered one of the most confusing parts of JavaScript, but it doesn't have to be. Most of the confusion stems from trying to figure out what this refers to where it is written.

In reality, the secret to understanding this is looking at who called the function. Think of it as a dynamic reference that changes based on the context of the call.

this in the Global Context

When you use this outside of any function or object, it refers to the Global Object.

  • In a Browser: this is the window.

  • In Node.js: this is the global object.

console.log(this); // Logs the Window object in a browser

this Inside Objects (The Method Context)

When a function is a property of an object (a method), this points to the object that "owns" that method at the moment it is called.

const devProfile = {
  username: "JS_Expert",
  printName: function() {
    console.log(`User: ${this.username}`);
  }
};

devProfile.printName(); // Logs: "User: JS_Expert"

In this case, devProfile is the caller. Because it triggered the function, this refers to devProfile.


this Inside Regular Functions

If you call a standalone function, this defaults to the Global Object (unless you are using 'strict mode').

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

checkContext(); // Logs the Window object

Even if the function is defined alone, it is technically called by the global environment.

How the "Caller" Changes this

The value of this is not permanent. It is determined at the call site. You can take the same function and give it a different this just by changing who calls it.

The "Borrowing" Example:

function showType() {
  console.log(`Device: ${this.type}`);
}

const workstation = { type: "PC", showType: showType };
const handheld = { type: "Tablet", showType: showType };

workstation.showType(); // Device: PC
handheld.showType();    // Device: Tablet

The function remains the same, but this shifts because the caller shifted from workstation to handheld.