Reusable object methods
A shared method needs to operate on whichever object calls it.
JS Puzzles · Const
JavaScript's regular-function this is determined by how the function is called, not where it is defined. Method calls provide the receiver, while standalone calls, explicit binding, constructors, and arrow functions follow different rules.
For a regular function, this is supplied by the call rather than fixed by where the function was written. A method call such as obj.method() supplies obj; detaching the method removes that receiver. Arrow functions do not provide their own this and instead capture it lexically.
thisconst user = {
name: "Ada",
greet() {
return `Hello, ${this.name}`;
},
};
const greet = user.greet;
console.log(user.greet()); // Hello, Ada
console.log(greet()); // Hello, undefined (or throws in strict mode)The same regular function receives different this values because it is called in different ways.
A shared method needs to operate on whichever object calls it.
A callback must preserve a particular receiver after being passed elsewhere.
The same function must run with different receivers or argument lists.
For a regular function, this is determined at runtime by invocation. In obj.method(), it is obj; in a standalone call, it is undefined in strict mode and usually the global object otherwise.
Follow-up: How can a method retain its receiver when passed as a callback? Use bind to create a function whose this binding does not change.
An arrow function does not have its own this binding. It uses the surrounding lexical this, so calling it as an object method does not make the object its this value.
Follow-up: What is a practical alternative when a callback needs the object as this? Use a regular function and bind the desired receiver, or call it through that object.
call and apply can explicitly provide this for one invocation, while bind creates a new function with a fixed this binding. These mechanisms are useful when a function is reused with different objects.
Follow-up: What happens if the same regular function is accessed through another object? Its this value changes to the object used for that call.
thisFunction.prototype.bind()Function.prototype.apply()Function.prototype.call()globalThisstrict modearrow functions