mozilla

Function.prototype.bind()

这篇翻译不完整。请帮忙从英语翻译这篇文章

概述

bind()方法会创建一个新函数,称为绑定函数.当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数.

语法

fun.bind(thisArg[, arg1[, arg2[, ...]]])

参数

thisArg
当绑定函数被调用时,该参数会作为原函数运行时的 this 指向.当使用new 操作符调用绑定函数时,该参数无效.
arg1, arg2, ...
当绑定函数被调用时,这些参数加上绑定函数本身的参数会按照顺序作为原函数运行时的参数.

描述

 
bind() 函数会创建一个新的函数(一个绑定的函数)有同样的函数体(在 ECMAScript 5 规范内置 Call 属性),当该函数(绑定函数的原函数)被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。绑定函数被调用时,bind() 也接受预设的参数提供给原函数。一个绑定函数也能使用 new 操作符 创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。
 

示例

示例: 创建绑定函数

bind() 最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的 this 值。JavaScript新手经常犯的一个错误是将一个方法从对象中拿出来,然后再调用,希望方法中的 this 是原来的对象。(比如在回调中传入这个方法。)如果不做特殊处理的话,一般会丢失原来的对象。从原来的函数和原来的对象创建一个绑定函数,则能很漂亮地解决这个问题:

this.x = 9; 
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, 因为在这个例子中,"this"指向全局对象

// 创建一个'this'绑定到module的函数
var boundGetX = getX.bind(module);
boundGetX(); // 81
 
 
 
 
 
 
 
 
 
 
 
 
 
 

示例: 分部函数

bind()的另一个最简单的用法是使一个函数拥有预设的初始参数.这些参数(如果有的话)作为bind()的第二个参数跟在this(或其他对象)后边,之后它们会被插入到目标函数的参数列表的前边,传递给绑定函数的参数会跟在这些参数的后边.

function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// 创建函数并给函数预设的打头参数
var leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
 
 
 
 
 
 
 
 
 
 
 

示例: 配合setTimeout

在默认情况下, 使用window.setTimeout()时,this 关键字会指向window (或全局) 对象. 当使用类的方法时,需要 this 引用类的实例,你可能需要显式的把 this 绑定到回调函数以便继续使用实例.

function LateBloomer() {
  this.petalCount = Math.ceil(Math.random() * 12) + 1;
}

// 1秒后声明bloom
LateBloomer.prototype.bloom = function() {
  window.setTimeout(this.declare.bind(this), 1000);
};

LateBloomer.prototype.declare = function() {
  console.log('I am a beautiful flower with ' +
    this.petalCount + ' petals!');
};
 
 
 
 
 
 
 
 
 
 
 
 
 

作为构造函数的绑定函数

警告 :这部分演示了Javascript的能力并且记录了bind()的超前用法. 以下展示的方法并不是最佳的解决方案且可能不应该用在任何生产环境中

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

var p = new Point(1, 2);
p.toString(); // '1,2'


var emptyObj = {};
var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
// not supported in the polyfill below,
// works fine with native bind:
var YAxisPoint = Point.bind(null, 0/*x*/);

var axisPoint = new YAxisPoint(5);
axisPoint.toString(); // '0,5'

axisPoint instanceof Point; // true
axisPoint instanceof YAxisPoint; // true
new Point(17, 42) instanceof YAxisPoint; // true
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Note that you need do nothing special to create a bound function for use with new. The corollary is that you need do nothing 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.

// Example can be run directly in your JavaScript console
// ...continuing from above

// Can still be called as a normal function 
// (although usually this is undesired)
YAxisPoint(13);

emptyObj.x + ',' + emptyObj.y;
// >  '0,13'
 
 
 
 
 
 
 
 
 

If you wish to support use of a bound function only using new, or only by calling it, the target function must enforce that restriction.

Example: Creating shortcuts

bind() is also helpful in cases where you want to create a shortcut to a function which requires a specific this value.

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:

var slice = Array.prototype.slice;

// ...

slice.call(arguments);
 
 
 
 
 

With bind(), this can be simplified. In the following piece of code, slice is a bound function to the call() function of Function.prototype, with the this value set to the slice() function of Array.prototype. This means that additional call() calls can be eliminated:

// same as "slice" in the previous example
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);

// ...

slice(arguments);
 

Polyfill

bind 函数在 ECMA-262 第五版才被加入;它可能无法在所有浏览器上运行。你可以部份地在脚本开头加入以下代码,就能使它运作,让不支持的浏览器也能使用 bind() 功能。

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis || window,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

Some of the many differences (there may well be others, as this list does not seriously attempt to be exhaustive) between this algorithm and the specified algorithm are:

  • The partial implementation relies Array.prototype.slice, Array.prototype.concat, Function.prototype.call and Function.prototype.apply, built-in methods to have their original values.
  • The partial implementation creates functions that do not have immutable "poison pill" caller and arguments properties that throw a TypeError upon get, set, or deletion. (This could be added if the implementation supports Object.defineProperty, or partially implemented [without throw-on-delete behavior] if the implementation supports the __defineGetter__ and __defineSetter__ extensions.)
  • The partial implementation creates functions that have a prototype property. (Proper bound functions have none.)
  • The partial implementation creates bound functions whose length property does not agree with that mandated by ECMA-262: it creates functions with length 0, while a full implementation, depending on the length of the target function and the number of pre-specified arguments, may return a non-zero length.

If you choose to use this partial implementation, you must not rely on those cases where behavior deviates from ECMA-262, 5th edition! With some care, however (and perhaps with additional modification to suit specific needs), this partial implementation may be a reasonable bridge to the time when bind() is widely implemented according to the specification.

Specifications

Specification Status Comment
ECMAScript 5.1 (ECMA-262)
Function.prototype.bind
Standard Initial definition. Implemented in JavaScript 1.8.5.
ECMAScript 6 (ECMA-262)
Function.prototype.bind
Release Candidate  
 

 

浏览器兼容性

Feature Firefox (Gecko) Chrome Internet Explorer Opera Safari
Basic support 4.0 (2) 7 9 11.60 5.1.4
Feature Chrome for Android Firefox Mobile (Gecko) Android IE Mobile Opera Mobile Safari Mobile
Basic support 0.16 4.0 (2) 4.0 ? 11.50 未实现

Based on Kangax's compat tables.

相关链接

文档标签和贡献者

向此页面作出贡献: teoli, ziyunfei, stylechen, bin, TooBug, SDLyu, paddingme, sensui7
最后编辑者: sensui7,