Function.prototype.bind
Creates a copy of a function with a fixed this and, optionally, arguments.
Available since: ES5
Syntax
fn.bind(thisArg, ...args)Parameters
| Parameter | Type | Description |
|---|---|---|
| thisArg | any | The this value for the new function. |
| ...args | any | Optional. Arguments to fix in advance. |
Return value
FunctionA new function with this and arguments bound.
Examples
A method loses this when passed on its own:
class User {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, ${this.name}`;
}
}
const anna = new User('Anna');
const lost = anna.greet;
const bound = anna.greet.bind(anna);
try {
lost();
} catch (error) {
console.log(error.name);
}
console.log(bound());Output:
TypeError
Hi, AnnaPartial application — fixing the first argument:
const multiply = (a, b) => a * b;
const triple = multiply.bind(null, 3);
console.log(triple(5));Output:
15Notes
The most common case is passing a method to an event handler or timer. An arrow function is often used instead of bind(): () => user.greet().
See also
- Function.prototype.call — Calls a function with a given this and arguments.
- Function.prototype.apply — Calls a function with a given this and an array of arguments.
- Arrow function (=>) — A short way to write a function.
In the tutorial
- this, call, apply and bind — How this is determined in JavaScript, why a method loses its context, and how to set this by hand with call, apply and bind.