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.
this Binding (Precedence Order)When a standalone function is called without any contextual owner:
this defaults to the global object (window in browsers)."use strict"): this is strictly undefined.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)
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!!"
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.
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);
}
};
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)
How does JavaScript achieve inheritance without classical classes? Proceed to: JavaScript Prototypes & Prototypal Inheritance →