This Keyword
This Keyword
Section titled βThis KeywordβWhat it means
Section titled βWhat it meansβthis refers to the object a function is executing βon behalf ofβ β but unlike most languages, its value in JavaScript is determined by how a function is called, not where itβs defined (with one major exception: arrow functions, which donβt have their own this and instead inherit it lexically from the surrounding scope).
Examples
Section titled βExamplesβconst person = { name: "Alice", greet() { console.log(`Hi, I'm ${this.name}`); },};
person.greet(); // "Hi, I'm Alice" -- `this` is `person`
const greetFn = person.greet;greetFn(); // "Hi, I'm undefined" -- `this` lost its binding!
const bound = person.greet.bind(person);bound(); // "Hi, I'm Alice" -- explicitly bound
const timer = { name: "Timer", start() { setTimeout(() => { console.log(this.name); // "Timer" -- arrow function inherits `this` from `start` }, 100); },};timer.start();Common mistake
Section titled βCommon mistakeβPassing an object method as a callback (e.g. to setTimeout or an event listener) without preserving its this binding β the function loses its connection to the original object when called that way.
class Button { constructor(label) { this.label = label; } handleClick() { console.log(`${this.label} clicked`); }}
const btn = new Button("Submit");element.addEventListener("click", btn.handleClick);// when clicked: "undefined clicked" -- `this` inside handleClick is no longer `btn`
// Fix: bind it, or use an arrow function wrapperelement.addEventListener("click", btn.handleClick.bind(btn));element.addEventListener("click", () => btn.handleClick());Quick practice
Section titled βQuick practiceβ-
What determines the value of
thisinside a regular function?Answer
How the function is called β e.g.obj.method()bindsthistoobj, while calling the same function standalone loses that binding. -
How does
thisbehave differently inside an arrow function?Answer
Arrow functions don't have their ownthisβ they inherit it lexically from the enclosing scope at the time they're defined, and it never changes based on how they're called. -
What does
.bind()do?Answer
Returns a new function permanently bound to a specificthisvalue, regardless of how that new function is later called.