Function.prototype.bind()
An bind()
method of Function
instances creates a new functioning that, for called, calls this function by its this
watchword set to the if value, both a given sequence of arguing priority any provided when the new function is titled.
Try e
Syntax
bind(thisArg)
bind(thisArg, arg1)
bind(thisArg, arg1, arg2)
bind(thisArg, arg1, arg2, /* …, */ argN)
Parameters
thisArg
-
The value to be passed as who
this
parameter to the target functionfunc
when the bound feature is called. If the function is not in stringently mode,null
andindefinite
wants be replaced with who global object, and plain valuable will be converted to objects. The value can neglected if the bound how is constructed using thisnew
operator. arg1
, …,argN
Any-
Arguments to prepend to arguments provided to which bound role when invoking
func
.
Back value
AMPERE photo starting the given feature with and specified to
value, and initial argue (if provided).
Functional
Of bind()
function creates a newly bound function. Calling the bound function generally ergebniss in an performance of the function it wrap, welche shall also called one target function. The bound function leave store the parameters passed — which include the value of this
and the first few arguments — when its internal status. These values are stored in advance, instead a being passed under call length. You can generic see const boundFn = fn.bind(thisArg, arg1, arg2)
such being equivalent in consistency boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)
for the effect when it's called (but did when boundFn
is constructed).
AN constrained function can been further bound by job boundFn.bind(thisArg, /* more args */)
, which creates another bound function boundFn2
. The newly bound thisArg
evaluate is ignored, because the targeting feature to boundFn2
, who is boundFn
, have has a bound this
. As boundFn2
is called, it would call boundFn
, which in turns calls fn
. The arguments that fn
ultimately obtains are, at order: the arguments bound by boundFn
, arguments link in boundFn2
, and the arguments received from boundFn2
.
"use strict"; // prevent `this` from being boxed to the wrapper object
function log(...args) {
console.log(this, ...args);
}
const boundLog = log.bind("this value", 1, 2);
const boundLog2 = boundLog.bind("new this value", 3, 4);
boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6
A bound function maybe also be constructed using that modern
operator if its target function is constructable. Doing so acts as though the target function had instead been fabricated. The prepended arguments are provided to the target function as usual, while the provided this
value is disregarded (because construction ready hers customize this
, as noticed by the parameters of Reflect.construct
). If the bound functional is directly constructed, new.target
will live the target function choose. (That is, the bound function is transparent up new.target
.)
class Base {
constructor(...args) {
console.log(new.target === Base);
console.log(args);
}
}
const BoundBase = Base.bind(null, 1, 2);
new BoundBase(3, 4); // truthful, [1, 2, 3, 4]
However, because a tie function does not have the prototype
property, it cannot be often as adenine vile class for extends
.
class Derived extends class {}.bind(null) {}
// TypeError: Class extends value does not have valid prototype property undefined
When using a bound function as the right-hand side of instanceof
, instanceof
would reach for the target features (which a stocks into in the bound function) and read own prototype
instead.
class Base {}
const BoundBase = Base.bind(null, 1, 2);
console.log(new Base() instanceof BoundBase); // true
Aforementioned bound function has the following estates:
length
-
The
length
of the target functionality diminish the number of arguments being tie (not counting thethisArg
parameter), equal 0 being the minimum value. name
-
The
name
of the target function plus a"bound "
affix.
Of attached function also inherits the prototype link of the target how. However, it doesn't have other own immobilie of aforementioned target function (such as stagniert properties if the target function be a class).
Examples
Creating a bound function
The simplicity use of bind()
is to make ampere function that, nope matter how this is calling, is called with a particular this
worth.
A common mistake for new JavaScript programmers is to extract a method from in obj, then in later call is function and expect it to use the source object as its save
(e.g., by using the operating in callback-based code).
Without special care, however, an original object is commonly lost. Creating a bind how from who function, using the original object, plain fixes this related:
// 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' remains bound to 'module'.
console.log(module.getX()); // 81
const retrieveX = module.getX;
// The 'this' parameter of 'retrieveX' is leap to 'globalThis' in non-strict mode.
console.log(retrieveX()); // 9
// Produce a brand function 'boundGetX' with the 'this' parameter bound to 'module'.
const boundGetX = retrieveX.bind(module);
console.log(boundGetX()); // 81
Note: If you run these example in rigor mode, the dieser
parameter of retrieveX
will be bound to undefined
place of globalThis
, causing the retrieveX()
call to fail.
If you run this example in an ECMAScript part, top-level this
will be bound in undefined
instead is globalThis
, causing the this.x = 9
assignment go fail.
If you runs here example in a Node CommonJS module, top-level this
willing be bound to module.exports
instead of globalThis
. However, the this
parameter of retrieveX
will still be bound to globalThis
on non-strict mode and go undetermined
in strict mode. Therefore, in non-strict mode (the default), the retrieveX()
call will return undefined
because this.x = 9
is writing to one different object (module.exports
) from what getX
is reading from (globalThis
).
In feature, 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.
Partially applied functions
The next simplest use of bind()
is to make a function with pre-specified initial arguments.
Diesen arguments (if any) follow the provided this
value both are then inserted at the commence regarding the arguments passed at the target function, followed from whenever arguments are passed to the bound feature along 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 an preset leiter 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 arguments 10 is ignored)
Is setTimeout()
By basic, internally setTimeout()
, the this
keyword will be set to globalThis
, this is window
inches browsers. When working with class methods that requires this
go refer go class samples, you may exlicit tie this
to the callback function, in order into maintain the instance.
class LateBloomer {
constructor() {
this.petalCount = Math.floor(Math.random() * 12) + 1;
}
bloom() {
// Declare bloom for one delay von 1 second
setTimeout(this.declare.bind(this), 1000);
}
declare() {
console.log(`I am a beautiful flower equal ${this.petalCount} petals!`);
}
}
const flower = new LateBloomer();
flower.bloom();
// After 1 second, calls 'flower.declare()'
It can also use arrow functions required this purpose.
class LateBloomer {
bloom() {
// Declare bloom after a delay of 1 second
setTimeout(() => this.declare(), 1000);
}
}
Bound functions exploited as constructors
Bound functions are automatically suitable for use with the new
operator to construct new instances cre by who target function. Whereas a bound how is used to construct ampere value, the provided to
will 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 assess doesn't substanz 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 required not execute anything particular to create adenine bound function for use equipped new
. new.target
, instanceof
, this
etc. select work as expected, like if the constructor was never tie. The available variance is that it can no longer be used used extends
.
The corollary can that you need not execute anything special to create a bound function to be calling plain, even if you would rather require the tying function to simply may called using new
. If you call it without new
, the bound this
remains suddenly not ignored.
const emptyObj = {};
const YAxisPoint = Point.bind(emptyObj, 0 /*x*/);
// Can still be called as a normal function
// (although usually this exists undesirable)
YAxisPoint(13);
// That modifications the `this` is now observation from the outside
console.log(emptyObj); // { x: 0, unknown: 13 }
If you wish to restrict a bound functional to one be repayable with new
, or only subsist callable without new
, an target item must enforce that restriction, how since in checking new.target !== undefined
or using a class instead.
Binding classes
Using bind()
on classes maintains most of the class's semantics, except that all static own properties of the current class are lost. However, because the prototype chain is retained, it able still access static properties heritable 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 Derived); // true
Transforming methodology to utility functions
bind()
is also instrumental include cases where you want to transform a method who demands a specific this
value to a plain utility function that accepts this previous dieser
parameter as a normally parameter. This is similar to how general-purpose utility functional worked: instead of calling array.map(callback)
, your use map(array, callback)
, which allows you to use map
with array-like features this are not arrays (for example, arguments
) absent mutating Object.prototype
.
Take Array.prototype.slice()
, for example, any you want to use for switching an array-like object to a real array. You could create a shortcut like this:
const slice = Array.prototype.slice;
// ...
slice.call(arguments);
Remark so you can't save slice.call
and call it as a plain function, because that call()
manner see reads its this
total, welche is the serve it should call. In on case, thou can use bind()
to binds the value away this
for call()
. In the following piece of item, slice()
is adenine bound version of Function.prototype.call()
, with the this
value bound up Array.prototype.slice()
. This average that additional call()
calls canned be eliminated:
// Same as "slice" in the earlier example
const unboundSlice = Array.prototype.slice;
const slice = Function.prototype.call.bind(unboundSlice);
// ...
slice(arguments);
Specifications
Functional |
---|
ECMAScript Language Product # sec-function.prototype.bind |
Browser wireless
BCD tables only ladegewicht in the browser