The this Keyword In Depth
📖 Concept
this is a special keyword that refers to the object that is executing the current function. Its value depends on HOW the function is called, not where it's defined (except arrow functions).
Rules (in order of precedence):
newbinding —this= the new object being created- Explicit binding —
call(),apply(),bind()setthisexplicitly - Implicit binding — When called as a method (
obj.fn()),this= the object before the dot - Default binding — In non-strict mode:
this=window/globalThis. In strict mode:this=undefined - Arrow functions — No own
this; inherits from enclosing lexical scope
🏠 Real-world analogy: this is like the word "I" in language. Who "I" refers to depends on who is speaking. If Alice says "I", it means Alice. If Bob says "I", it means Bob. The context determines the meaning.
💻 Code Example
1// Implicit binding — method call2const user = {3 name: "Alice",4 greet() {5 console.log(`Hi, I'm ${this.name}`);6 }7};8user.greet(); // "Hi, I'm Alice" — this = user910// Lost this — common bug!11const greetFn = user.greet;12greetFn(); // "Hi, I'm undefined" — this = window (or undefined in strict)1314// Explicit binding15function sayHi() {16 console.log(`Hi, I'm ${this.name}`);17}18const bob = { name: "Bob" };19sayHi.call(bob); // "Hi, I'm Bob"20sayHi.apply(bob); // "Hi, I'm Bob"21const boundSayHi = sayHi.bind(bob);22boundSayHi(); // "Hi, I'm Bob"2324// call vs apply — arguments differ25function introduce(greeting, punctuation) {26 console.log(`${greeting}, I'm ${this.name}${punctuation}`);27}28introduce.call(bob, "Hey", "!"); // args individually29introduce.apply(bob, ["Hey", "!"]); // args as array3031// Arrow functions — lexical this32const team = {33 name: "Engineering",34 members: ["Alice", "Bob"],35 showMembers() {36 // Arrow function inherits 'this' from showMembers37 this.members.forEach((member) => {38 console.log(`${member} is in ${this.name}`); // ✅ Works!39 });40 }41};42team.showMembers();4344// new binding45function Person(name) {46 this.name = name;47 // 'this' refers to the newly created object48}49const alice = new Person("Alice");50console.log(alice.name); // "Alice"5152// this in event handlers53// button.addEventListener("click", function() {54// console.log(this); // The button element (implicit binding)55// });56// button.addEventListener("click", () => {57// console.log(this); // window/undefined — arrow function!58// });
🏋️ Practice Exercise
Mini Exercise:
- Create an object method that loses
thiswhen extracted — then fix it withbind - Write examples demonstrating all 4 binding rules
- Use
callto borrow a method from one object to use on another - Explain why
thisin asetTimeoutcallback isn't the object, and fix it
⚠️ Common Mistakes
Extracting a method loses
this:const fn = obj.method; fn()—thisis no longerobjUsing regular functions in
forEach/mapinside methods —thiswon't refer to the object; use arrow functionsArrow functions DON'T have their own
this— don't use them as object methodsForgetting that
bindreturns a NEW function — it doesn't modify the originalIn event handlers,
this= the element in regular functions, NOT in arrow functions
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for The this Keyword In Depth. Login to unlock this feature.