Not Bound
Methods in JavaScript are not bound to their object by default (unlike class methods in languages like Python).
This means that if you extract a method from an object and pass it around as a “callback” function, it will completely lose track of its original this context.
The Disconnected Method
const user = {
name: "Lane",
sayHi() {
console.log(`Hi, my name is ${this.name}`);
},
};
// This works perfectly:
user.sayHi(); // "Hi, my name is Lane"
// Extracting the method into a standalone variable
const standaloneSayHi = user.sayHi;
// Calling it standalone causes an error!
standaloneSayHi();
// TypeError: Cannot read properties of undefined (reading 'name')
Because standaloneSayHi was called without the user. prefix, the this context evaluated to undefined, causing a crash.
The Solution: .bind()
If you need to pass a method into another function as a callback, you must explicitly lock its context using the .bind() method.
const user = {
firstName: "Lane",
getFullName() { return this.firstName; }
};
function getGreeting(callbackFunc) {
return "Hello, " + callbackFunc();
}
// Create a copy of the method forever bound to the 'user' object
const boundMethod = user.getFullName.bind(user);
console.log(getGreeting(boundMethod));
// Output: "Hello, Lane"