Why Does JavaScript’s this Change When a Method Becomes a Callback?

Asked 6 days ago 65 views

0

I understand why user.greet() can use the user object, but I get tripped up when I pass that same method somewhere else as a callback. It may work when called directly, then fail or produce an unexpected value after being detached.

"use strict";

// The method reads name from whichever object is bound as this.
const user = {
  name: "Mina",
  greet() {
    return `Hi, ${this.name}`;
  }
};

// Calling through user binds this to user.
console.log(user.greet());

// Saving the method alone does not preserve that object binding.
const callback = user.greet;
console.log(callback());

Is the key idea that this depends on how a function is called rather than where it was written? I’d also like to know when people reach for bind() versus an arrow function in real code.

0 Answers


Write Your Answer