this in Different Contexts

The keyword this in JavaScript behaves differently depending on where and how it is used. Understanding its value in various contexts is essential for writing correct and predictable code.

Illustration of this_in_different_contexts
Illustration of this_in_different_contexts

💡 Key Concept

this refers to the object that is executing the current function.

1. Global Context

Outside of any function, this refers to the global object.

  • In browsers, the global object is window.
  • In Node.js, it is global.

📌 Deep Dive: this in Global Scope

JAVASCRIPT
console.log(this === window); // true (in browser)
Output
true

2. Function Context

Inside a regular function, this depends on how the function is called:

Function Call vs Method Call
Call TypeValue of this
Simple function callundefined in strict mode, window otherwise
Method call (object.function())Object owning the method

📌 Deep Dive: this in Function vs Method

JAVASCRIPT
function show() {
  console.log(this);
}

const obj = {
  show: show
};

show();     // In strict mode: undefined; otherwise global object
obj.show(); // obj
Output
undefined (strict mode)
[object Object]

3. Arrow Functions

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

📌 Deep Dive: Arrow Function this

JAVASCRIPT
const obj = {
  value: 42,
  arrowFunc: () => {
    console.log(this.value);
  },
  regularFunc() {
    const innerArrow = () => console.log(this.value);
    innerArrow();
  }
};

obj.arrowFunc(); // undefined (this from global scope)
obj.regularFunc(); // 42 (this from obj)
Output
undefined
42

4. Constructor Functions and Classes

When a function is called with new, this refers to the newly created object.

📌 Deep Dive: this in Constructors

JAVASCRIPT
function Person(name) {
  this.name = name;
}

const p = new Person("Alice");
console.log(p.name); // Alice
Output
Alice

5. Explicit Binding: call, apply, and bind

You can explicitly set this using call, apply, or bind.

📌 Deep Dive: Explicitly setting this

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

const user = { name: "Bob" };

greet.call(user);  // Bob
greet.apply(user); // Bob

const boundGreet = greet.bind(user);
boundGreet();      // Bob
Output
Bob
Bob
Bob

⚠️ Common Pitfall

Using this inside nested functions often results in unexpected this values because each function defines its own this. Use arrow functions or bind to maintain the proper context.

Summary Table

this Value in Different Contexts
Contextthis Value
Global scopeGlobal object (window in browsers)
Regular function callundefined (strict mode) or global object
Method callThe object owning the method
Arrow functionLexical this (from surrounding context)
Constructor (with new)The new instance object
Explicit binding (call, apply, bind)Object passed as first argument