Preserve a method receiver
Passing an object method as a timer or callback.
JS Puzzles · Const
JavaScript’s this for regular functions comes from the call form, not the definition. Use bind to create a callable function with a fixed this and optional initial arguments.
For regular functions, this is selected when the function is called. Calling through object.method() makes the object the receiver; extracting the method removes that receiver, while bind creates a callable function with a fixed this. Arrow functions instead use the surrounding lexical this.
let bound = func.bind(context, [arg1], [arg2], ...);| Name | Type | Description |
|---|---|---|
context | any | The object or value to use as this when the bound function is called. |
args | any[] | Optional leading arguments supplied to the original function before call-time arguments. |
A bound variant of the original function with the selected this value and any preset leading arguments.
this; the function's definition location does not.bind returns another callable function-like value rather than changing the original function.bind can preset both the receiver and leading arguments.bind when an object method must be handed to a callback without losing its receiver.this may no longer refer to the original object.bind is called.const user = { name: "Ada", show() { return this.name; } };
const detached = user.show;
console.log(detached());
console.log(user.show());
const bound = user.show.bind(user);
console.log(bound());The method call supplies the object as this; detaching the function loses that receiver, while bind preserves it.
Passing an object method as a timer or callback.
Reusing one function with a chosen object context.
Supplying arguments before a callback is invoked.
bind()arrow functionsobject methodssetTimeout