aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/global_objects/function/bind/index.html
blob: 45ee18de4603f3a844f6f89ddefded433eb10c97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
---
title: Function.prototype.bind()
slug: Web/JavaScript/Reference/Global_Objects/Function/bind
tags:
  - ECMAScript 2015
  - ECMAScript 5
  - Function
  - JavaScript
  - Method
  - polyfill
translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind
---
<div>{{JSRef}}</div>

<p><code><strong>bind()</strong></code> 方法创建一个新的函数,在 <code>bind()</code> 被调用时,这个新函数的 <code>this</code> 被指定为 <code>bind()</code> 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。</p>

<div>{{EmbedInteractiveExample("pages/js/function-bind.html", "taller")}}</div>



<h2 id="语法">语法</h2>

<pre class="syntaxbox"><code><var>function</var></code>.bind(<var>thisArg</var>[, <var>arg1</var>[, <var>arg2</var>[, ...]]])</pre>

<h3 id="参数">参数</h3>

<dl>
 <dt><code>thisArg</code></dt>
 <dd>调用绑定函数时作为 <code>this</code> 参数传递给目标函数的值。 如果使用{{jsxref("Operators/new", "new")}}运算符构造绑定函数,则忽略该值。当使用 <code>bind</code><code>setTimeout</code> 中创建一个函数(作为回调提供)时,作为 <code>thisArg</code> 传递的任何原始值都将转换为 <code>object</code>。如果 <code>bind</code> 函数的参数列表为空,或者<code>thisArg</code><code>null</code><code>undefined</code>,执行作用域的 <code>this</code> 将被视为新函数的 <code>thisArg</code></dd>
 <dt><code>arg1, arg2, ...</code></dt>
 <dd>当目标函数被调用时,被预置入绑定函数的参数列表中的参数。</dd>
</dl>

<h3 id="返回值">返回值</h3>

<p>返回一个原函数的拷贝,并拥有指定的 <strong><code>this</code></strong> 值和初始参数。</p>

<h2 id="描述">描述</h2>

<div><strong>bind()</strong> 函数会创建一个新的<strong>绑定函数</strong><strong>bound function</strong>,BF)。绑定函数是一个 exotic function object(怪异函数对象,ECMAScript 2015 中的术语),它包装了原函数对象。调用<strong>绑定函数</strong>通常会导致执行<strong>包装函数</strong><br>
<strong>绑定函数</strong>具有以下内部属性:</div>

<div></div>

<div>
<ul>
 <li><strong>[[BoundTargetFunction]]</strong> - 包装的函数对象</li>
 <li><strong>[[BoundThis]]</strong> - 在调用包装函数时始终作为 <strong>this</strong> 值传递的值。</li>
 <li><strong>[[BoundArguments]]</strong> - 列表,在对包装函数做任何调用都会优先用列表元素填充参数列表。</li>
 <li><strong>[[Call]]</strong> - 执行与此对象关联的代码。通过函数调用表达式调用。内部方法的参数是一个<strong>this</strong>值和一个包含通过调用表达式传递给函数的参数的列表。</li>
</ul>

<p>当调用绑定函数时,它调用 <strong>[[BoundTargetFunction]]</strong> 上的内部方法 <strong>[[Call]]</strong>,就像这样 <strong>Call(<em>boundThis</em>, <em>args</em>)</strong>。其中,<strong>boundThis</strong><strong>[[BoundThis]]</strong><strong>args</strong><strong>[[BoundArguments]]</strong> 加上通过函数调用传入的参数列表。</p>
</div>

<div>
<p>绑定函数也可以使用 {{jsxref("Operators/new", "new")}} 运算符构造,它会表现为目标函数已经被构建完毕了似的。提供的 <code>this</code> 值会被忽略,但前置参数仍会提供给模拟函数。</p>
</div>

<h2 id="示例">示例</h2>

<h3 id="创建绑定函数">创建绑定函数</h3>

<p><code>bind()</code> 最简单的用法是创建一个函数,不论怎么调用,这个函数都有同样的 <strong><code>this</code></strong> 值。JavaScript新手经常犯的一个错误是将一个方法从对象中拿出来,然后再调用,期望方法中的 <code>this</code> 是原来的对象(比如在回调中传入这个方法)。如果不做特殊处理的话,一般会丢失原来的对象。基于这个函数,用原始的对象创建一个绑定函数,巧妙地解决了这个问题:</p>

<pre class="brush: js">this.x = 9;    // 在浏览器中,this 指向全局的 "window" 对象
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var retrieveX = module.getX;
retrieveX();
// 返回 9 - 因为函数是在全局作用域中调用的

// 创建一个新函数,把 'this' 绑定到 module 对象
// 新手可能会将全局变量 x 与 module 的属性 x 混淆
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81
</pre>

<h3 id="偏函数">偏函数</h3>

<p><code>bind()</code> 的另一个最简单的用法是使一个函数拥有预设的初始参数。只要将这些参数(如果有的话)作为 <code>bind()</code> 的参数写在 <code>this</code> 后面。当绑定函数被调用时,这些参数会被插入到目标函数的参数列表的开始位置,传递给绑定函数的参数会跟在它们后面。</p>

<pre class="brush: js">function list() {
  return Array.prototype.slice.call(arguments);
}

function addArguments(arg1, arg2) {
    return arg1 + arg2
}

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

var result1 = addArguments(1, 2); // 3

// 创建一个函数,它拥有预设参数列表。
var leadingThirtysevenList = list.bind(null, 37);

// 创建一个函数,它拥有预设的第一个参数
var addThirtySeven = addArguments.bind(null, 37);

var list2 = leadingThirtysevenList();
// [37]

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

var result2 = addThirtySeven(5);
// 37 + 5 = 42

var result3 = addThirtySeven(5, 10);
// 37 + 5 = 42 ,第二个参数被忽略
</pre>

<h3 id="配合_setTimeout">配合 <code>setTimeout</code></h3>

<p>在默认情况下,使用 {{ domxref("window.setTimeout()") }} 时,<code>this</code> 关键字会指向 {{ domxref("window") }} (或 <code>global</code>)对象。当类的方法中需要 <code>this</code> 指向类的实例时,你可能需要显式地把 <code>this</code> 绑定到回调函数,就不会丢失该实例的引用。</p>

<pre class="brush: js"><code>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!');
};

var flower = new LateBloomer();
flower.bloom();  // 一秒钟后, 调用 'declare' 方法</code></pre>

<h3 id="作为构造函数使用的绑定函数">作为构造函数使用的绑定函数</h3>

<div class="warning">
<p><strong>警告</strong> :这部分演示了 JavaScript 的能力并且记录了 <code>bind()</code> 的超前用法。以下展示的方法并不是最佳的解决方案,且可能不应该用在任何生产环境中。</p>
</div>

<p>绑定函数自动适应于使用 {{jsxref("Operators/new", "new")}} 操作符去构造一个由目标函数创建的新实例。当一个绑定函数是用来构建一个值的,原来提供的 <code>this</code> 就会被忽略。不过提供的参数列表仍然会插入到构造函数调用时的参数列表之前。</p>

<pre class="brush: js">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*/);

// 本页下方的 polyfill 不支持运行这行代码,
// 但使用原生的 bind 方法运行是没问题的:

var YAxisPoint = Point.bind(null, 0/*x*/);

/*(译注:polyfill 的 bind 方法中,如果把 bind 的第一个参数加上,
即对新绑定的 this 执行 Object(this),包装为对象,
因为 Object(null) 是 {},所以也可以支持)*/

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

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

<p>请注意,你不需要做特别的处理就可以创建一个和 {{jsxref("Operators/new", "new")}} 操作符一起使用的绑定函数。也就是说,你不需要做特别处理就可以创建一个可以被直接调用的绑定函数,即使你更希望绑定函数是用 {{jsxref("Operators/new", "new")}} 操作符来调用。</p>

<pre class="brush: js">// ...接着上面的代码继续的话,
// 这个例子可以直接在你的 JavaScript 控制台运行

// 仍然能作为一个普通函数来调用
// (即使通常来说这个不是被期望发生的)
YAxisPoint(13);

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

<p>如果你希望一个绑定函数要么只能用 {{jsxref("Operators/new", "new")}} 操作符,要么只能直接调用,那你必须在目标函数上显式规定这个限制。</p>

<h3 id="快捷调用">快捷调用</h3>

<p>在你想要为一个需要特定的 <strong><code>this</code></strong> 值的函数创建一个捷径(shortcut)的时候,<code>bind()</code> 也很好用。</p>

<p>你可以用 {{jsxref("Array.prototype.slice")}} 来将一个类似于数组的对象(array-like object)转换成一个真正的数组,就拿它来举例子吧。你可以简单地这样写:</p>

<pre class="brush: js">var slice = Array.prototype.slice;

// ...

slice.apply(arguments);</pre>

<p><code>bind()</code>可以使这个过程变得简单。在下面这段代码里面,<code>slice</code>{{jsxref("Function.prototype")}}{{jsxref("Function.prototype.apply()", "apply()")}} 方法的绑定函数,并且将 {{jsxref("Array.prototype")}}{{jsxref("Array.prototype.slice()", "slice()")}} 方法作为 <strong><code>this</code></strong> 的值。这意味着我们压根儿用不着上面那个 <code>apply()</code>调用了。</p>

<pre class="brush: js">// 与前一段代码的 "slice" 效果相同
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.apply.bind(unboundSlice);

// ...

slice(arguments);</pre>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">规范</th>
   <th scope="col">状态</th>
   <th scope="col">备注</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>初始定义。在 JavaScript 1.8.5 中实现。</td>
  </tr>
  <tr>
   <td>{{SpecName('ES2015', '#sec-function.prototype.bind', 'Function.prototype.bind')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>



<p>{{Compat("javascript.builtins.Function.bind")}}</p>

<h2 id="相关链接">相关链接</h2>

<ul>
 <li><code>Function.prototype.bind</code> 的 polyfill 可以参考 <a href="https://github.com/zloirock/core-js#ecmascript-function">core-js</a></li>
 <li>{{jsxref("Function.prototype.apply()")}}</li>
 <li>{{jsxref("Function.prototype.call()")}}</li>
 <li>{{jsxref("Functions", "函数")}}</li>
</ul>