Function.prototype.bind()

Function 实例的 bind() 方法创建一个新函数,该函数在被调用时调用该函数,并将其 this 关键字设置为提供的值,并在调用新函数时在任何提供的参数之前提供给定的参数序列。

¥The bind() method of Function instances creates a new function that, when called, calls this function with its this keyword set to the provided value, and a given sequence of arguments preceding any provided when the new function is called.

Try it

语法

¥Syntax

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

参数

¥Parameters

thisArg

当调用绑定函数时,要作为 this 参数传递给目标函数 func 的值。如果函数不在 严格模式 中,则 nullundefined 将被替换为全局对象,并且原始值将被转换为对象。如果绑定函数是使用 new 运算符构造的,则该值将被忽略。

arg1, …, argN Optional

调用 func 时要添加到提供给绑定函数的参数前面的参数。

返回值

¥Return value

具有指定 this 值和初始参数(如果提供)的给定函数的副本。

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

描述

¥Description

bind() 函数创建一个新的绑定函数。调用绑定函数通常会导致执行它所封装的函数,该函数也称为目标函数。绑定函数将存储传递的参数(包括 this 的值和前几个参数)作为其内部状态。这些值是提前存储的,而不是在调用时传递。通常,你可以将 const boundFn = fn.bind(thisArg, arg1, arg2) 视为与 const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs) 在调用时的效果等效(但在构造 boundFn 时则不然)。

¥The bind() function creates a new bound function. Calling the bound function generally results in the execution of the function it wraps, which is also called the target function. The bound function will store the parameters passed — which include the value of this 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 see const boundFn = fn.bind(thisArg, arg1, arg2) as being equivalent to const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs) for the effect when it's called (but not when boundFn is constructed).

可以通过调用 boundFn.bind(thisArg, /* more args */) 进一步绑定绑定函数,这会创建另一个绑定函数 boundFn2。新绑定的 thisArg 值将被忽略,因为 boundFn2 的目标函数(即 boundFn)已经绑定了 this。当调用 boundFn2 时,它会调用 boundFn,而 boundFn 又调用 fnfn 最终收到的参数按顺序为:boundFn 绑定的参数、boundFn2 绑定的参数以及 boundFn2 接收的参数。

¥A bound function can be further bound by calling boundFn.bind(thisArg, /* more args */), which creates another bound function boundFn2. The newly bound thisArg value is ignored, because the target function of boundFn2, which is boundFn, already has a bound this. When boundFn2 is called, it would call boundFn, which in turn calls fn. The arguments that fn ultimately receives are, in order: the arguments bound by boundFn, arguments bound by boundFn2, and the arguments received by boundFn2.

js
"use strict"; // prevent `this` from being boxed into 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

如果目标函数是可构造的,则也可以使用 new 运算符来构造绑定函数。这样做就像已经构建了目标函数一样。前面的参数照常提供给目标函数,而提供的 this 值将被忽略(因为构造准备了自己的 this,如 Reflect.construct 的参数所示)。如果直接构造绑定函数,则 new.target 将成为目标函数。(即绑定函数对于 new.target 来说是透明的。)

¥A bound function may also be constructed using the new 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 provided this value is ignored (because construction prepares its own this, as seen by the parameters of Reflect.construct). If the bound function is directly constructed, new.target will be the target function instead. (That is, the bound function is transparent to new.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]

但是,由于绑定函数不具有 prototype 属性,因此它不能用作 extends 的基类。

¥However, because a bound function does not have the prototype property, it cannot be used as a base class for extends.

js
class Derived extends class {}.bind(null) {}
// TypeError: Class extends value does not have valid prototype property undefined

当使用绑定函数作为 instanceof 的右侧时,instanceof 将到达目标函数(该函数内部存储在绑定函数中)并读取其 prototype

¥When using a bound function as the right-hand side of instanceof, instanceof would reach for the target function (which is stored internally in the bound function) and read its prototype 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

目标函数的 length 减去绑定的参数数量(不包括 thisArg 参数),其中 0 为最小值。

name

目标函数的 name 加上 "bound " 前缀。

绑定函数还继承了目标函数的 原型链。但是,它不具有目标函数的其他属性(例如,如果目标函数是类,则为 静态属性)。

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

示例

¥Examples

创建绑定函数

¥Creating a bound function

bind() 最简单的用途是创建一个函数,无论如何调用它,都会使用特定的 this 值来调用。

¥The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value.

JavaScript 新程序员的一个常见错误是从对象中提取方法,然后调用该函数并期望它使用原始对象作为其 this(例如,通过在基于回调的代码中使用该方法)。

¥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:

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()); // 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

注意:如果在 严格模式 中运行此示例,则 retrieveXthis 参数将绑定到 undefined 而不是 globalThis,从而导致 retrieveX() 调用失败。

¥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.

如果在 ECMAScript 模块中运行此示例,顶层 this 将绑定到 undefined 而不是 globalThis,从而导致 this.x = 9 分配失败。

¥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.

如果你在 Node CommonJS 模块中运行此示例,则顶层 this 将绑定到 module.exports 而不是 globalThis。但是,retrieveXthis 参数在非严格模式下仍将绑定到 globalThis,在严格模式下仍将绑定到 undefined。因此,在非严格模式(默认)下,retrieveX() 调用将返回 undefined,因为 this.x = 9 正在写入与 getX 正在读取的对象 (globalThis) 不同的对象 (module.exports)。

¥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).

事实上,一些内置的 "methods" 也是返回绑定函数的 getter - 一个值得注意的例子是 Intl.NumberFormat.prototype.format(),它在访问时返回一个绑定函数,你可以直接将其作为回调传递。

¥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.

部分应用函数

¥Partially applied functions

bind() 的下一个最简单的用途是使用预先指定的初始参数创建一个函数。

¥The next simplest use of bind() is to make a function with pre-specified initial arguments.

这些参数(如果有)遵循提供的 this 值,然后插入到传递给目标函数的参数的开头,后面是调用绑定函数时传递给绑定函数的任何参数。

¥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.

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 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)

使用 setTimeout()

¥With setTimeout()

默认情况下,在 setTimeout() 内,this 关键字将设置为 globalThis,即浏览器中的 window。当使用需要 this 引用类实例的类方法时,你可以显式地将 this 绑定到回调函数,以维护该实例。

¥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.

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 use arrow 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

绑定函数自动适合与 new 运算符一起使用来构造由目标函数创建的新实例。当使用绑定函数构造值时,提供的 this 将被忽略。但是,提供的参数仍会添加到构造函数调用之前。

¥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.

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 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

请注意,你无需执行任何特殊操作即可创建与 new 一起使用的绑定函数。new.targetinstanceofthis 等都按预期工作,就好像构造函数从未绑定过一样。唯一的区别是它不能再用于 extends

¥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.

推论是,即使你宁愿要求仅使用 new 调用绑定函数,你也无需执行任何特殊操作来创建要简单调用的绑定函数。如果你在没有 new 的情况下调用它,绑定的 this 突然不会被忽略。

¥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.

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

如果你希望限制绑定函数只能使用 new 调用,或者只能在没有 new 的情况下调用,则目标函数必须强制执行该限制,例如通过检查 new.target !== undefined 或使用 class 代替。

¥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.

绑定类

¥Binding classes

在类上使用 bind() 保留了类的大部分语义,但当前类的所有静态自有属性都会丢失。但是,由于原型链被保留,你仍然可以访问从父类继承的静态属性。

¥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.

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

将方法转换为效用函数

¥Transforming methods to utility functions

如果你想要将需要特定 this 值的方法转换为接受先前 this 参数作为普通参数的普通实用程序函数,那么 bind() 也很有用。这类似于通用实用函数的工作方式:你不调用 array.map(callback),而是使用 map(array, callback),这允许你将 map 与非数组的类数组对象(例如 arguments)一起使用,而无需更改 Object.prototype

¥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 allows you to use map with array-like objects that are not arrays (for example, arguments) without mutating Object.prototype.

Array.prototype.slice() 为例,你要使用它来将类似数组的对象转换为真正的数组。你可以创建这样的快捷方式:

¥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:

js
const slice = Array.prototype.slice;

// ...

slice.call(arguments);

请注意,你无法保存 slice.call 并将其作为普通函数调用,因为 call() 方法还会读取其 this 值,这是它应该调用的函数。此时,可以使用 bind()call() 绑定 this 的值。在下面的代码中,slice()Function.prototype.call() 的绑定版本,其中 this 值绑定到 Array.prototype.slice()。这意味着可以消除额外的 call() 调用:

¥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:

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

// ...

slice(arguments);

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看