Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Function.prototype.bind()

BaselineWidely available

Thebind() method ofFunction instances creates a new function that, when called, calls this function with itsthis keyword set to the provided value, and a given sequence of arguments preceding any provided when the new function is called.

Try it

const module = {  x: 42,  getX() {    return this.x;  },};const unboundGetX = module.getX;console.log(unboundGetX()); // The function gets invoked at the global scope// Expected output: undefinedconst boundGetX = unboundGetX.bind(module);console.log(boundGetX());// Expected output: 42

Syntax

js
bind(thisArg)bind(thisArg, arg1)bind(thisArg, arg1, arg2)bind(thisArg, arg1, arg2, /* …, */ argN)

Parameters

thisArg

The value to be passed as thethis parameter to the target functionfunc when the bound function is called. If the function is not instrict mode,null andundefined will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using thenew operator.

arg1, …,argNOptional

Arguments to prepend to arguments provided to the bound function when invokingfunc.

Return value

A copy of the given function with the specifiedthis value, and initial arguments (if provided).

Description

Thebind() function creates a newbound function. Calling the bound function generally results in the execution of the function it wraps, which is also called thetarget function. The bound function will store the parameters passed — which include the value ofthis and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally seeconst boundFn = fn.bind(thisArg, arg1, arg2) as being equivalent toconst boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs) for the effect when it's called (but not whenboundFn is constructed).

A bound function can be further bound by callingboundFn.bind(thisArg, /* more args */), which creates another bound functionboundFn2. The newly boundthisArg value is ignored, because the target function ofboundFn2, which isboundFn, already has a boundthis. WhenboundFn2 is called, it would callboundFn, which in turn callsfn. The arguments thatfn ultimately receives are, in order: the arguments bound byboundFn, arguments bound byboundFn2, and the arguments received byboundFn2.

js
"use strict"; // prevent `this` from being boxed into the wrapper objectfunction 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 may also be constructed using thenew operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the providedthis value is ignored (because construction prepares its ownthis, as seen by the parameters ofReflect.construct). If the bound function is directly constructed,new.target will be the target function instead. (That is, the bound function is transparent tonew.target.)

js
class Base {  constructor(...args) {    console.log(new.target === Base);    console.log(args);  }}const BoundBase = Base.bind(null, 1, 2);new BoundBase(3, 4); // true, [1, 2, 3, 4]

However, because a bound function does not have theprototype property, it cannot be used as a base class forextends.

js
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 ofinstanceof,instanceof would reach for the target function (which is stored internally in the bound function) and read itsprototype instead.

js
class Base {}const BoundBase = Base.bind(null, 1, 2);console.log(new Base() instanceof BoundBase); // true

The bound function has the following properties:

length

Thelength of the target function minus the number of arguments being bound (not counting thethisArg parameter), with 0 being the minimum value.

name

Thename of the target function plus a"bound " prefix.

The bound function also inherits theprototype chain of the target function. However, it doesn't have other own properties of the target function (such asstatic properties if the target function is a class).

Examples

Creating a bound function

The most common use ofbind() is to make a function that, no matter how it is called, is called with a particularthis 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 itsthis (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:

js
// 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()); // 81const 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 instrict mode, thethis parameter ofretrieveX will be bound toundefined instead ofglobalThis, causing theretrieveX() call to fail.

If you run this example in an ECMAScript module, top-levelthis will be bound toundefined instead ofglobalThis, causing thethis.x = 9 assignment to fail.

If you run this example in a Node CommonJS module, top-levelthis will be bound tomodule.exports instead ofglobalThis. However, thethis parameter ofretrieveX will still be bound toglobalThis in non-strict mode and toundefined in strict mode. Therefore, in non-strict mode (the default), theretrieveX() call will returnundefined becausethis.x = 9 is writing to a different object (module.exports) from whatgetX is reading from (globalThis).

In fact, some built-in "methods" are also getters that return bound functions — one notable example beingIntl.NumberFormat.prototype.format(), which, when accessed, returns a bound function that you can directly pass as a callback.

Partially applied functions

Another use ofbind() is to make a function with pre-specified initial arguments.

These arguments (if any) follow the providedthis 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.

js
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 argumentconst 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)); // 42console.log(addThirtySeven(5, 10)); // 42// (the last argument 10 is ignored)

With setTimeout()

By default, withinsetTimeout(), thethis keyword will be set toglobalThis, which iswindow in browsers. When working with class methods that requirethis to refer to class instances, you may explicitly bindthis to the callback function, in order to maintain the instance.

js
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 usearrow functions for this purpose.

js
class LateBloomer {  bloom() {    // Declare bloom after a delay of 1 second    setTimeout(() => this.declare(), 1000);  }}

Bound functions used as constructors

Bound functions are automatically suitable for use with thenew operator to construct new instances created by the target function. When a bound function is used to construct a value, the providedthis is ignored. However, provided arguments are still prepended to the constructor call.

js
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 ignoredconst YAxisPoint = Point.bind(null, 0 /* x */);const axisPoint = new YAxisPoint(5);axisPoint.toString(); // '0,5'axisPoint instanceof Point; // trueaxisPoint instanceof YAxisPoint; // truenew YAxisPoint(17, 42) instanceof Point; // true

Note that you need not do anything special to create a bound function for use withnew.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 forextends.

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 usingnew. If you call it withoutnew, the boundthis is suddenly not ignored.

js
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 outsideconsole.log(emptyObj); // { x: 0, y: 13 }

If you wish to restrict a bound function to only be callable withnew, or only be callable withoutnew, the target function must enforce that restriction, such as by checkingnew.target !== undefined or using aclass instead.

Binding classes

Usingbind() 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.

js
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); // undefinedconsole.log(new BoundDerived() instanceof Derived); // true

Transforming methods to utility functions

bind() is also helpful in cases where you want to transform a method which requires a specificthis value to a plain utility function that accepts the previousthis parameter as a normal parameter. This is similar to how general-purpose utility functions work: instead of callingarray.map(callback), you usemap(array, callback), which allows you to usemap with array-like objects that are not arrays (for example,arguments) without mutatingObject.prototype.

TakeArray.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:

js
const slice = Array.prototype.slice;// …slice.call(arguments);

Note that you can't saveslice.call and call it as a plain function, because thecall() method also reads itsthis value, which is the function it should call. In this case, you can usebind() to bind the value ofthis forcall(). In the following piece of code,slice() is a bound version ofFunction.prototype.call(), with thethis value bound toArray.prototype.slice(). This means that additionalcall() calls can be eliminated:

js
// Same as "slice" in the previous exampleconst unboundSlice = Array.prototype.slice;const slice = Function.prototype.call.bind(unboundSlice);// …slice(arguments);

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-function.prototype.bind

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp