aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html
blob: 006db2aa4c0adfebd13356824fd31ce29d23c30e (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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
---
title: Function.prototype.bind()
slug: Web/JavaScript/Reference/Global_Objects/Function/bind
translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind
---
<div>{{JSRef}}</div>

<p><code><strong>bind()</strong></code> 方法,會建立一個新函式。該函式被呼叫時,會將 <code>this</code> 關鍵字設為給定的參數,並在呼叫時,帶有提供之前,給定順序的參數。</p>

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

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

<h3 id="參數">參數</h3>

<dl>
 <dt><code>thisArg</code></dt>
 <dd>The value to be passed as the <code>this</code> parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the {{jsxref("Operators/new", "new")}} operator.</dd>
 <dt><code>arg1, arg2, ...</code></dt>
 <dd>Arguments to prepend to arguments provided to the bound function when invoking the target function.</dd>
</dl>

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

<p>A copy of the given function with the specified <strong><code>this</code></strong> value and initial arguments.</p>

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

<p><strong>bind()</strong> 函式建立了一個新的<strong>綁定函式(BF)</strong><strong>BF</strong> 是個包裝了原有函式物件的 <strong>exotic function object</strong><strong>ECMAScript 2015</strong> 的術語)。通常,呼叫 <strong>BF</strong> 會執行該 <strong>wrapped function</strong><strong> BF</strong> 含有以下內部屬性:</p>

<ul>
 <li><strong>[[BoundTargetFunction]] </strong>- the wrapped function object;</li>
 <li><strong>[[BoundThis]]</strong> - the value that is always passed as <strong>this</strong> value when calling the wrapped function.</li>
 <li><strong>[[BoundArguments]]</strong> - a list of values whose elements are used as the first arguments to any call to the wrapped function.</li>
 <li><strong>[[Call]]</strong> - executes code associated with this object. Invoked via a function call expression. The arguments to the internal method are a <strong>this</strong> value and a list containing the arguments passed to the function by a call expression.</li>
</ul>

<p>When bound function is called, it calls internal method<strong> [[Call]]</strong> on <strong>[[BoundTargetFunction]], </strong>with following arguments <strong>Call(<em>boundThis</em>, <em>args</em>).</strong> Where, <strong><em>boundThis </em></strong>is <strong>[[BoundThis]]</strong>, <em><strong>args </strong></em>is <strong>[[BoundArguments]]</strong> followed by the arguments passed by the function call.</p>

<p>A bound function may also be constructed using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new" title="The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function."><code>new</code></a> operator: doing so acts as though the target function had instead been constructed. The provided <strong><code>this</code></strong> value is ignored, while prepended arguments are provided to the emulated function.</p>

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

<h3 id="建立綁定函式">建立綁定函式</h3>

<p>The simplest use of <code>bind()</code> is to make a function that, no matter how it is called, is called with a particular <strong><code>this</code></strong> 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 its <code>this</code> (e.g. by using that 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:</p>

<pre class="brush: js">this.x = 9;    // this refers to global "window" object here in the browser
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var retrieveX = module.getX;
retrieveX();
// returns 9 - The function gets invoked at the global scope

// Create a new function with 'this' bound to module
// New programmers might confuse the
// global var x with module's property x
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81
</pre>

<h3 id="Partially_applied_functions">Partially applied functions</h3>

<p>The next simplest use of <code>bind()</code> is to make a function with pre-specified initial arguments. These arguments (if any) follow the provided <code>this</code> value and are then inserted at the start of the arguments passed to the target function, followed by the arguments passed to the bound function, whenever the bound function is called.</p>

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

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

// Create a function with a preset leading argument
var leadingThirtysevenList = list.bind(null, 37);

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

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

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

<p>By default within {{domxref("window.setTimeout()")}}, the <code>this</code> keyword will be set to the {{ domxref("window") }} (or <code>global</code>) object. When working with class methods that require <code>this</code> to refer to class instances, you may explicitly bind <code>this</code> to the callback function, in order to maintain the instance.</p>

<pre class="brush: js">function LateBloomer() {
  this.petalCount = Math.floor(Math.random() * 12) + 1;
}

// Declare bloom after a delay of 1 second
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();
// after 1 second, triggers the 'declare' method</pre>

<h3 id="Bound_functions_used_as_constructors">Bound functions used as constructors</h3>

<div class="warning">
<p><strong>Warning:</strong> This section demonstrates JavaScript capabilities and documents some edge cases of the <code>bind()</code> method. The methods shown below are not the best way to do things and probably should not be used in any production environment.</p>
</div>

<p>Bound functions are automatically suitable for use with the {{jsxref("Operators/new", "new")}} operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided <code>this</code> is ignored. However, provided arguments are still prepended to the constructor call:</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'

// not supported in the polyfill below,

// works fine with native bind:

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


var emptyObj = {};
var YAxisPoint = Point.bind(emptyObj, 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
</pre>

<p>Note that you need do nothing special to create a bound function for use with {{jsxref("Operators/new", "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 {{jsxref("Operators/new", "new")}}.</p>

<pre class="brush: js">// 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;
// &gt;  '0,13'
</pre>

<p>If you wish to support the use of a bound function only using {{jsxref("Operators/new", "new")}}, or only by calling it, the target function must enforce that restriction.</p>

<h3 id="Creating_shortcuts">Creating shortcuts</h3>

<p><code>bind()</code> is also helpful in cases where you want to create a shortcut to a function which requires a specific <strong><code>this</code></strong> value.</p>

<p>Take {{jsxref("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:</p>

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

// ...

slice.apply(arguments);
</pre>

<p>With <code>bind()</code>, this can be simplified. In the following piece of code, <code>slice</code> is a bound function to the {{jsxref("Function.prototype.apply()", "apply()")}} function of {{jsxref("Function.prototype")}}, with the <strong><code>this</code></strong> value set to the {{jsxref("Array.prototype.slice()", "slice()")}} function of {{jsxref("Array.prototype")}}. This means that additional <code>apply()</code> calls can be eliminated:</p>

<pre class="brush: js">// same as "slice" in the previous example
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.apply.bind(unboundSlice);

// ...

slice(arguments);
</pre>

<h2 id="Polyfill">Polyfill</h2>

<p>You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of <code>bind()</code> in implementations that do not natively support it.</p>

<pre class="brush: js">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
                 ? this
                 : oThis,
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    if (this.prototype) {
      // Function.prototype doesn't have a prototype property
      fNOP.prototype = this.prototype;
    }
    fBound.prototype = new fNOP();

    return fBound;
  };
}
</pre>

<p>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:</p>

<ul>
 <li>The partial implementation relies on {{jsxref("Array.prototype.slice()")}}, {{jsxref("Array.prototype.concat()")}}, {{jsxref("Function.prototype.call()")}} and {{jsxref("Function.prototype.apply()")}}, built-in methods to have their original values.</li>
 <li>The partial implementation creates functions that do not have immutable "poison pill" {{jsxref("Function.caller", "caller")}} and <code>arguments</code> properties that throw a {{jsxref("Global_Objects/TypeError", "TypeError")}} upon get, set, or deletion. (This could be added if the implementation supports {{jsxref("Object.defineProperty")}}, or partially implemented [without throw-on-delete behavior] if the implementation supports the {{jsxref("Object.defineGetter", "__defineGetter__")}} and {{jsxref("Object.defineSetter", "__defineSetter__")}} extensions.)</li>
 <li>The partial implementation creates functions that have a <code>prototype</code> property. (Proper bound functions have none.)</li>
 <li>The partial implementation creates bound functions whose {{jsxref("Function.length", "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.</li>
</ul>

<p>If you choose to use this partial implementation, <strong>you must not rely on those cases where behavior deviates from ECMA-262, 5th edition!</strong> 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 <code>bind()</code> is widely implemented according to the specification.</p>

<p>Please check <a href="https://github.com/Raynos/function-bind">https://github.com/Raynos/function-bind</a> for a more thorough solution!</p>

<h2 id="規範">規範</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition. Implemented in 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>

<div>{{CompatibilityTable}}</div>

<div>
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Edge</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome("7")}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoDesktop("2")}}</td>
   <td>{{CompatIE("9")}}</td>
   <td>{{CompatOpera("11.60")}}</td>
   <td>{{CompatSafari("5.1")}}</td>
  </tr>
 </tbody>
</table>
</div>

<div>
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Edge</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatAndroid("4.0")}}</td>
   <td>{{CompatChrome("1")}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoMobile("2")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatOperaMobile("11.5")}}</td>
   <td>{{CompatSafari("6.0")}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="相關連結">相關連結</h2>

<ul>
 <li>{{jsxref("Function.prototype.apply()")}}</li>
 <li>{{jsxref("Function.prototype.call()")}}</li>
 <li>{{jsxref("Functions", "Functions", "", 1)}}</li>
</ul>