JavaScript 'this' Keyword: The 4 Rules of Binding, Call, Apply & Bind

The this keyword in JavaScript represents the execution context of a function. Unlike variable scoping (which is static and lexical), this binding for regular functions is dynamic—it is determined entirely by how the function is invoked at runtime.

The 4 Rules of this Binding (Precedence Order)

1. Default Binding (Standalone Function Invocations)

When a standalone function is called without any contextual owner:

  • In non-strict mode: this defaults to the global object (window in browsers).
  • In strict mode ("use strict"): this is strictly undefined.

2. Implicit Binding (Method Calls)

When a function is invoked as a method of an object, this points to the object preceding the dot:

const student = {
    name: "Vikram",
    greet() {
        console.log(`Hello, my name is ${this.name}`);
    }
};
student.greet(); // "Hello, my name is Vikram" (this === student)

3. Explicit Binding: call(), apply() & bind()

Forcefully dictates what this should point to:

function introduce(greeting, punctuation) {
    console.log(`${greeting}, I am ${this.name}${punctuation}`);
}

const userA = { name: "Aarav" };
const userB = { name: "Pooja" };

// 1. call(): Comma-separated arguments; executes immediately
introduce.call(userA, "Namaste", "!"); // "Namaste, I am Aarav!"

// 2. apply(): Arguments inside an ARRAY; executes immediately
introduce.apply(userB, ["Hello", "."]); // "Hello, I am Pooja."

// 3. bind(): Returns a NEW bound function without executing immediately
const boundIntroduce = introduce.bind(userA, "Welcome");
boundIntroduce("!!"); // "Welcome, I am Aarav!!"

4. new Binding (Constructor Functions)

When a function is invoked with the new keyword, a brand-new empty object is created, and this points directly to that new instance.

Arrow Functions: Lexical this (The Game Changer)

Arrow functions do NOT have their own this. They resolve this lexically from their enclosing lexical scope, completely fixing the classic timer callback bug:

const timer = {
    seconds: 0,
    start() {
        // Arrow function inherits 'this' from start() method!
        setInterval(() => {
            this.seconds++;
            console.log("Elapsed:", this.seconds);
        }, 1000);
    }
};

University Exam Corner (BCA Examination Notes)

Exam Precedence Summary:
1. new Keyword Binding (Highest Priority)
2. Explicit Binding via bind(), call(), apply()
3. Implicit Binding via contextual object (obj.method())
4. Default Binding (Global / undefined in strict mode - Lowest Priority)

Next Step

How does JavaScript achieve inheritance without classical classes? Proceed to: JavaScript Prototypes & Prototypal Inheritance →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!