Skip to content

This Keyword

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).

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();

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 wrapper
element.addEventListener("click", btn.handleClick.bind(btn));
element.addEventListener("click", () => btn.handleClick());
  1. What determines the value of this inside a regular function?

    AnswerHow the function is called β€” e.g. obj.method() binds this to obj, while calling the same function standalone loses that binding.
  2. How does this behave differently inside an arrow function?

    AnswerArrow functions don't have their own this β€” they inherit it lexically from the enclosing scope at the time they're defined, and it never changes based on how they're called.
  3. What does .bind() do?

    AnswerReturns a new function permanently bound to a specific this value, regardless of how that new function is later called.