The bind()
method does not invoke a function but instead takes an existing function and creates a new function with a specified value for "this" inside the new function.
The syntax of the bind()
method is:
bind(thisArg, arg1, arg2, ….) //
arg1 and arg2 are optional
The simplest use of bind()
is to make a function that, no matter how it is called, is called with a particular this
value.
A common mistake for new JavaScript programmers is to extract a
method from an object, then to later call that function and expect it to
use the original object as its this
(e.g., by using the method in callback-based code).
Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:
// Top-level 'this' is bound to 'globalThis' in scripts. this.x = 9; const module = { x: 81, getX() { return this.x; }, }; // The 'this' parameter of 'getX' is bound to 'module'. console.log(module.getX()); // 81 const retrieveX = module.getX; // The 'this' parameter of 'retrieveX' is bound to 'globalThis' in non-strict mode. console.log(retrieveX()); // 9 // Create a new function 'boundGetX' with the 'this' parameter bound to 'module'. const boundGetX = retrieveX.bind(module); console.log(boundGetX()); // 81
Note: If you run this example in strict mode, the this
parameter of retrieveX
will be bound to undefined
instead of globalThis
, causing the retrieveX()
call to fail.
If you run this example in an ECMAScript module, top-level this
will be bound to undefined
instead of globalThis
, causing the this.x = 9
assignment to fail.
If you run this example in a Node CommonJS module, top-level this
will be bound to module.exports
instead of globalThis
. However, the this
parameter of retrieveX
will still be bound to globalThis
in non-strict mode and to undefined
in strict mode. Therefore, in non-strict mode (the default), the retrieveX()
call will return undefined
because this.x = 9
is writing to a different object (module.exports
) from what getX
is reading from (globalThis
).
In fact, some built-in "methods" are also getters that return bound functions - one notable example being Intl.NumberFormat.prototype.format()
, which, when accessed, returns a bound function that you can directly pass as a callback.
The next simplest use of bind()
is to make a function with pre-specified initial arguments.
These arguments (if any) follow the provided this
value
and are then inserted at the start of the arguments passed to the target
function, followed by whatever arguments are passed to the bound
function at the time it is called.
function list(...args) { return args; } function addArguments(arg1, arg2) { return arg1 + arg2; } console.log(list(1, 2, 3)); // [1, 2, 3] console.log(addArguments(1, 2)); // 3 // Create a function with a preset leading argument const leadingThirtySevenList = list.bind(null, 37); // Create a function with a preset first argument. const addThirtySeven = addArguments.bind(null, 37); console.log(leadingThirtySevenList()); // [37] console.log(leadingThirtySevenList(1, 2, 3)); // [37, 1, 2, 3] console.log(addThirtySeven(5)); // 42 console.log(addThirtySeven(5, 10)); // 42 // (the last argument 10 is ignored)
By default, within setTimeout()
, the this
keyword will be set to globalThis
, which is window
in browsers. When working with class methods that require this
to refer to class instances, you may explicitly bind this
to the callback function, in order to maintain the instance.
class LateBloomer { constructor() { this.petalCount = Math.floor(Math.random() * 12) + 1; } bloom() { // Declare bloom after a delay of 1 second setTimeout(this.declare.bind(this), 1000); } declare() { console.log(`I am a beautiful flower with ${this.petalCount} petals!`); } } const flower = new LateBloomer(); flower.bloom(); // After 1 second, calls 'flower.declare()'
You can also use arrow functions for this purpose.
class LateBloomer { bloom() { // Declare bloom after a delay of 1 second setTimeout(() => this.declare(), 1000); } }
Bound functions are automatically suitable for use with the new
operator to construct new instances created by the target function.
When a bound function is used to construct a value, the provided this
is ignored. However, provided arguments are still prepended to the constructor call.
function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function () { return `${this.x},${this.y}`; }; const p = new Point(1, 2); p.toString(); // '1,2' // The thisArg's value doesn't matter because it's ignored const YAxisPoint = Point.bind(null, 0 /*x*/); const axisPoint = new YAxisPoint(5); axisPoint.toString(); // '0,5' axisPoint instanceof Point; // true axisPoint instanceof YAxisPoint; // true new YAxisPoint(17, 42) instanceof Point; // true
Note that you need not do anything special to create a bound function for use with new
. new.target
, instanceof
, this
etc. all work as expected, as if the constructor was never bound. The only difference is that it can no longer be used for extends
.
The corollary is that you need not do anything special to create a
bound function to be called plainly, even if you would rather require
the bound function to only be called using new
. If you call it without new
, the bound this
is suddenly not ignored.
const emptyObj = {}; const YAxisPoint = Point.bind(emptyObj, 0 /*x*/); // Can still be called as a normal function // (although usually this is undesirable) YAxisPoint(13); // The modifications to `this` is now observable from the outside console.log(emptyObj); // { x: 0, y: 13 }
If you wish to restrict a bound function to only be callable with new
, or only be callable without new
, the target function must enforce that restriction, such as by checking new.target !== undefined
or using a class instead.
Using bind()
on classes preserves most of the class's semantics, except that all
static own properties of the current class are lost. However, because
the prototype chain is preserved, you can still access static properties
inherited from the parent class.
class Base { static baseProp = "base"; } class Derived extends Base { static derivedProp = "derived"; } const BoundDerived = Derived.bind(null); console.log(BoundDerived.baseProp); // "base" console.log(BoundDerived.derivedProp); // undefined console.log(new BoundDerived() instanceof
bind()
is also helpful in cases where you want to transform a method which requires a specific this
value to a plain utility function that accepts the previous this
parameter as a normal parameter. This is similar to how general-purpose utility functions work: instead of calling array.map(callback)
, you use map(array, callback)
, which avoids mutating Array.prototype
, and allows you to use map
with array-like objects that are not arrays (for example, arguments
).
Take Array.prototype.slice()
, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:
const slice = Array.prototype.slice; // ... slice.call(arguments);
Note that you can't save slice.call
and call it as a plain function, because the call()
method also reads its this
value, which is the function it should call. In this case, you can use bind()
to bind the value of this
for call()
. In the following piece of code, slice()
is a bound version of Function.prototype.call()
, with the this
value bound to Array.prototype.slice()
. This means that additional call()
calls can be eliminated:
// Same as "slice" in the previous example const unboundSlice = Array.prototype.slice; const slice = Function.prototype.call.bind(unboundSlice); // ... slice(arguments);