Function.prototype.bind()

  • Revision slug: JavaScript/Reference/Global_Objects/Function/bind
  • Revision title: bind
  • Revision id: 5045
  • Created:
  • Creator: fusionchess
  • Is current revision? No
  • Comment 195 words added, 53 words removed

Revision Content

{{ js_minversion_header("1.8.5") }}

Summary

Creates a new function that, when called, itself calls this function in the context of the provided this value, with a given sequence of arguments preceding any provided when the new function was called.

Method of Function
Implemented in JavaScript 1.8.5
ECMAScript Edition ECMAScript 5th Edition

Syntax

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

Parameters

thisArg
The value to be passed as the this parameter to the target function when the bound function is called.  The value is ignored if the bound function is constructed using the new operator.
arg1, arg2, ...
Arguments to prepend to arguments provided to the bound function when invoking the target function.

Description

The bind function creates a new function (a bound function) with the same function body (internal Call attribute in ECMAScript 5 terms) than the function it is being called on (the bound function's target function) with the this value bound to the first argument of bind, which cannot be overridden. bind also accepts leading default arguments to provide to the target function when the bound function is called.  A bound function may also be constructed using the new operator: doing so acts as though the target function had instead been constructed.  The provided this value is ignored, while prepended arguments are provided to the emulated function.

Compatibility

bind is a recent addition to ECMA-262, 5th edition; as such it may not be present in all browsers. 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 bind in implementations that do not natively support it.

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

Examples

Creating a bound function

The simplest use of bind is to make a function that, no matter how it is called, is called with a particular this 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 this (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:

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

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

Currying

The next simplest use of bind is to make a function with pre-specified initial arguments. 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 the arguments passed to the bound function, whenever the bound function is called.

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 leadingZeroList = list.bind(undefined, 37);

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

Bound functions used as constructors

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

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

axisPoint instanceof Point; // true
axisPoint instanceof YAxisPoint; // true
new Point(17, 42) instanceof YAxisPoint; // false with native bind // true, when using the above polyfill

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

Supplemental

One interesting wrinkle of bound functions working "as expected" with the new operator is that it is now possible to implement what one might call "Function.prototype.construct", an analog to Function.prototype.apply that takes an array of values as its sole argument, constructing this function with the provided arguments using the new operator:

// Function.prototype.construct will work with the Function.prototype.bind defined above

if (!Function.prototype.construct) { 
  Function.prototype.construct = function(aArgs) {

    if (aArgs.constructor !== Array)
      throw new TypeError("second argument to Function.prototype.construct must be an array");

    var aBoundArgs = Array.prototype.concat.apply([null], aArgs), 
        fBound = this.bind.apply(this, aBoundArgs);
        
    return new fBound();

  };
}

// Now consider the string "2011-7-16 19:35:46". Without an analog of the Function.apply method for constructors,
// you would run a lot of steps in order to construct a Date object from it:

var aDateArgs = "2011-7-16 19:35:46".split(/[- :]/),
    oMyDate1 = new Date(aDateArgs[0], aDateArgs[1], aDateArgs[2], aDateArgs[3], aDateArgs[4], aDateArgs[5]);
alert(oMyDate1.toLocaleString());


// With the Function.construct method we could do the same thing with a single step:
var oMyDate2 = Date.construct("2011-7-16 19:35:46".split(/[- :]/));
alert(oMyDate2.toLocaleString());

// Here is another example:

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function() { 
  return this.x + "," + this.y; 
};

alert(Point.construct([2, 4]).toString()); // "2,4"

But note well: the efficiency of constructing a new function every time you wish to construct an object by invoking a bound function via new with a variable number of arguments is questionable. Your code will be faster and more efficient if you use Function.prototype.apply instead, with normal call syntax rather than using new operator-based syntax.

Browser compatibility

Based on Kangax's compat tables

{{ CompatibilityTable() }}

Feature Firefox (Gecko) Chrome Internet Explorer Opera Safari
Basic support 4 7 9 {{ CompatNo() }} {{ CompatNo() }}
Feature Firefox Mobile (Gecko) Android IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}

See also

Revision Source

<p>{{ js_minversion_header("1.8.5") }}</p>
<h2 name="Summary">Summary</h2>
<p>Creates a new function that, when called, itself calls this function in the context of the provided <code>this</code> value, with a given sequence of arguments preceding any provided when the new function was called.</p>
<table class="standard-table"> <thead> <tr> <th class="header" colspan="2">Method of <a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/JavaScript/Reference/Global_Objects/Function"><code>Function</code></a></th> </tr> </thead> <tbody> <tr> <td>Implemented in</td> <td>JavaScript 1.8.5</td> </tr> <tr> <td>ECMAScript Edition</td> <td>ECMAScript 5th Edition</td> </tr> </tbody>
</table>
<h2 name="Syntax">Syntax</h2>
<p><code><em>fun</em>.bind(<em>thisArg</em>[, <em>arg1</em>[, <em>arg2</em>[, ...]]])</code></p>
<h2 name="Parameters">Parameters</h2>
<dl> <dt>thisArg</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 <a href="/en/JavaScript/Reference/Operators/Special/new" title="en/JavaScript/Reference/Operators/Special Operators/new Operator"><code>new</code> operator</a>.</dd> <dt>arg1, arg2, ...</dt> <dd>Arguments to prepend to arguments provided to the bound function when invoking the target function.</dd>
</dl>
<h2 name="Description">Description</h2>
<p>The <code>bind</code> function creates a new function (a <em>bound function</em>) with the same function body (internal <a href="/Call" title="Call">Call</a> attribute in ECMAScript 5 terms) than the function it is being called on (the bound function's <em>target function</em>) with the <code>this</code> value bound to the first argument of <code>bind</code>, which cannot be overridden. <code>bind</code> also accepts leading default arguments to provide to the target function when the bound function is called.  A bound function may also be constructed using the <code>new</code> operator: doing so acts as though the target function had instead been constructed.  The provided <code>this</code> value is ignored, while prepended arguments are provided to the emulated function.</p>
<h2 name="Compatibility">Compatibility</h2>
<p><code>bind</code> is a recent addition to ECMA-262, 5th edition; as such it may not be present in all browsers. 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 fBound 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 || window, aArgs.concat(Array.prototype.slice.call(arguments)));    
        };

    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 <code>Array.prototype.slice</code>, <code>Array.prototype.concat</code>, <code>Function.prototype.call</code> and <code>Function.prototype.apply</code>, built-in methods to have their original values.</li> <li>The partial implementation creates functions that do not have immutable "poison pill" <code>caller</code> and <code>arguments</code> properties that throw a <code>TypeError</code> upon get, set, or deletion. (This could be added if the implementation supports <a href="/en/JavaScript/Reference/Global_Objects/Object/defineProperty" title="en/JavaScript/Reference/Global Objects/Object/defineProperty"><code>Object.defineProperty</code></a>, or partially implemented [without throw-on-delete behavior] if the implementation supports the <a href="/en/JavaScript/Reference/Global_Objects/Object/defineGetter" title="en/JavaScript/Reference/Global Objects/Object/defineGetter"><code>__defineGetter__</code></a> and <a href="/en/JavaScript/Reference/Global_Objects/Object/defineSetter" title="en/JavaScript/Reference/Global Objects/Object/defineSetter"><code>__defineSetter__</code></a> 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 <code>length</code> 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>
<h2 name="Examples">Examples</h2>
<h3>Creating a bound function</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 <code>this</code> 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">var x = 9; 
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
</pre>
<h3>Currying</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 leadingZeroList = list.bind(undefined, 37);

var list2 = leadingZeroList(); // [37]
var list3 = leadingZeroList(1, 2, 3); // [37, 1, 2, 3]
</pre>
<h3>Bound functions used as constructors</h3>
<p>Bound functions are automatically suitable for use with the <code>new</code> 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"


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; // false with native bind // true, when using the above polyfill
</pre>
<p>Note that you need do nothing special to create a bound function for use with <code>new</code>. 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 <code>new</code>. If you wish to support use of a bound function only using <code>new</code>, or only by calling it, the target function must enforce that restriction.</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>
<h2 name="Supplemental">Supplemental</h2>
<p>One interesting wrinkle of bound functions working "as expected" with the <code>new</code> operator is that it is now possible to implement what one might call "<code>Function.prototype.construct</code>", an analog to <code><a href="/en/JavaScript/Reference/Global_Objects/Function/apply" title="en/JavaScript/Reference/Global Objects/Function/apply">Function.prototype.apply</a></code> that takes an array of values as its sole argument, constructing this function with the provided arguments using the <code>new</code> operator:</p>
<pre class="brush: js">// Function.prototype.construct will work with the Function.prototype.bind defined above

if (!Function.prototype.construct) { 
  Function.prototype.construct = function(aArgs) {

    if (aArgs.constructor !== Array)
      throw new TypeError("second argument to Function.prototype.construct must be an array");

    var aBoundArgs = Array.prototype.concat.apply([null], aArgs), 
        fBound = this.bind.apply(this, aBoundArgs);
        
    return new fBound();

  };
}

// Now consider the string "2011-7-16 19:35:46". Without an analog of the Function.apply method for constructors,
// you would run a lot of steps in order to construct a Date object from it:

var aDateArgs = "2011-7-16 19:35:46".split(/[- :]/),
    oMyDate1 = new Date(aDateArgs[0], aDateArgs[1], aDateArgs[2], aDateArgs[3], aDateArgs[4], aDateArgs[5]);
alert(oMyDate1.toLocaleString());


// With the Function.construct method we could do the same thing with a single step:
var oMyDate2 = Date.construct("2011-7-16 19:35:46".split(/[- :]/));
alert(oMyDate2.toLocaleString());

// Here is another example:

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function() { 
  return this.x + "," + this.y; 
};

alert(Point.construct([2, 4]).toString()); // "2,4"
</pre>
<p>But note well: the efficiency of constructing a new function every time you wish to construct an object by invoking a bound function via <code>new</code> with a variable number of arguments is questionable. Your code will be faster and more efficient if you use <code>Function.prototype.apply</code> instead, with normal call syntax rather than using <code>new</code> operator-based syntax.</p>
<h2>Browser compatibility</h2>
<p>Based on <a class=" external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat tables</a></p>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
<table class="compat-table"> <tbody> <tr> <th>Feature</th> <th>Firefox (Gecko)</th> <th>Chrome</th> <th>Internet Explorer</th> <th>Opera</th> <th>Safari</th> </tr> <tr> <td>Basic support</td> <td>4</td> <td>7</td> <td>9</td> <td>{{ CompatNo() }}</td> <td>{{ CompatNo() }}</td> </tr> </tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table"> <tbody> <tr> <th>Feature</th> <th>Firefox Mobile (Gecko)</th> <th>Android</th> <th>IE Mobile</th> <th>Opera Mobile</th> <th>Safari Mobile</th> </tr> <tr> <td>Basic support</td> <td>{{ CompatUnknown() }}</td> <td>{{ CompatUnknown() }}</td> <td>{{ CompatUnknown() }}</td> <td>{{ CompatUnknown() }}</td> <td>{{ CompatUnknown() }}</td> </tr> </tbody>
</table>
</div>
<h2 name="See_also">See also</h2>
<ul> <li><code><a href="/en/JavaScript/Reference/Global_Objects/Function/apply" title="en/JavaScript/Reference/Global Objects/Function/apply">Function.prototype.apply</a></code></li> <li><code><a href="/en/JavaScript/Reference/Global_Objects/Function/call" title="en/JavaScript/Reference/Global Objects/Function/call">Function.prototype.call</a></code></li>
</ul>
Revert to this revision