Function.prototype.bind()

  • Revision slug: JavaScript/Reference/Global_Objects/Function/bind
  • Revision title: bind
  • Revision id: 5003
  • Created:
  • Creator: Fatbrain
  • Is current revision? No
  • Comment Removed unnecessary comment about partial-implementation limitation from the compatibility code-snippet.; 29 words removed

Revision Content

{{ js_minversion_header("1.8.5") }}

This method is compliant with ECMAScript 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.

Syntax

var bound = fun.bind(thisValue [, arg1 [, arg2 [...] ] ]);

Parameters

thisValue
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) that calls the function that is its this value (the bound function's target function) with a specified this parameter, 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.

// PARTIAL WORKAROUND for Function.prototype.bind
if (!Function.prototype.bind)
    Function.prototype.bind = function(context /*, arg1, arg2... */) {
        'use strict';
        if (typeof this !== 'function') throw new TypeError();
        var _arguments = Array.prototype.slice.call(arguments, 1),
            _this = this,
            _concat = Array.prototype.concat,
            _function = function() {
                return _this.apply(this instanceof _dummy ? this : context,
                    _concat.apply(_arguments, arguments));
            },
            _dummy = function() {};
        _dummy.prototype = _this.prototype;
        _function.prototype = new _dummy();
        return _function;
};

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, when used with the new operator does not work correctly with the instanceof operator. Instances created using the unbounded constructor will not be an instance-of the bounded constructor.
  • The partial implementation relies upon a number of built-in methods and property names 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

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:

// Creating a function that always uses a particular this value
var x = 42;
var obj =
  {
    getX: function() { return this.x; },
    x: 17
  };

print(obj.getX()); // 17: called with obj as this

var getX = obj.getX;
print(getX());     // 42: called with global object as this


var boundGetX = getX.bind(obj); // this now fixed as obj
print(boundGetX()); // 17: calls obj.getX with obj as this

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.

// Creating a function that calls another function with pre-specified leading arguments
function List()
{
  var a = [];
  for (var i = 0; i < arguments.length; i++)
    a.push(arguments[i]);
  return a;
}

var l1 = List(1, 2, 3); // [1, 2, 3]

var LeadingZeroList = List.bind(null /* this */, 0);

var l2 = LeadingZeroList(); // [0]
var l3 = LeadingZeroList(1); // [0, 1]
var l4 = LeadingZeroList(1, 2); // [0, 1, 2]

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:

// Constructing with a bound function
function Point(x, y)
{
  this.x = x;
  this.y = y;
}
Point.prototype.toString = function() { return this.x + "," + this.y; };

print(new Point(1, 2)); // "1,2"

var thisObj = {};
var YAxisPoint = Point.bind(thisObj, 0 /* x */);

print(new YAxisPoint(5)); // "0,5": note thisObj is ignored

print(new YAxisPoint(17) instanceof Point);      // true
print(new YAxisPoint(17) instanceof YAxisPoint); // true again
print(new Point(17, 42) instanceof YAxisPoint);  // true as well (NOTE: this will be false in the partial implementation)

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.

// ...continuing from above

// Can still be called as a normal function (although usually this is undesired)
YAxisPoint(13);
print(thisObj.x + "," + thisObj.y); // "0,13"

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:

// NB: This code will work with the partial implementation of
//     Function.prototype.bind given above.
if (!Function.prototype.construct)
{
  Function.prototype.construct = function(args)
  {
    var boundArgs = Array.prototype.concat.apply([null], args);
    var boundFun = this.bind.apply(this, boundArgs);
    return new boundFun();
  };
}

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

var p1 = [2, 4];
print(Point.construct(p1)); // "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.

See also

Revision Source

<p>{{ js_minversion_header("1.8.5") }}</p>
<p>This method is compliant with ECMAScript 5.</p>
<h3 name="Summary">Summary</h3>
<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>
<h3 name="Syntax">Syntax</h3>
<p><code>var bound = fun.bind(<em>thisValue</em> [, <em>arg1</em> [, <em>arg2</em> [...] ] ]);</code></p>
<h3 name="Parameters">Parameters</h3>
<dl> <dt>thisValue</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>
<h3 name="Description">Description</h3>
<p>The <code>bind</code> function creates a new function (a <em>bound function</em>) that calls the function that is its <code>this</code> value (the bound function's <em>target function</em>) with a specified <code>this</code> parameter, 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>
<h3 name="Compatibility">Compatibility</h3>
<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">// PARTIAL WORKAROUND for Function.prototype.bind
if (!Function.prototype.bind)
    Function.prototype.bind = function(context /*, arg1, arg2... */) {
        'use strict';
        if (typeof this !== 'function') throw new TypeError();
        var _arguments = Array.prototype.slice.call(arguments, 1),
            _this = this,
            _concat = Array.prototype.concat,
            _function = function() {
                return _this.apply(this instanceof _dummy ? this : context,
                    _concat.apply(_arguments, arguments));
            },
            _dummy = function() {};
        _dummy.prototype = _this.prototype;
        _function.prototype = new _dummy();
        return _function;
};
</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, when used with the <code style="color: inherit; font-weight: inherit; ">new</code> operator does not work correctly with the <code style="color: inherit; font-weight: inherit; "><a href="/en/JavaScript/Reference/Operators/Special/instanceof" style="text-decoration: none; color: rgb(4, 137, 183) !important; cursor: default; " title="en/JavaScript/Reference/Operators/Special/instanceof">instanceof</a></code><a href="/en/JavaScript/Reference/Operators/Special/instanceof" style="text-decoration: none; color: rgb(4, 137, 183) !important; cursor: default; " title="en/JavaScript/Reference/Operators/Special/instanceof"> operator</a>. Instances created using the unbounded constructor will not be an instance-of the bounded constructor.</li> <li>The partial implementation relies upon a number of built-in methods and property names 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>
<h3 name="Examples">Examples</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">// Creating a function that always uses a particular this value
var x = 42;
var obj =
  {
    getX: function() { return this.x; },
    x: 17
  };

print(obj.getX()); // 17: called with obj as this

var getX = obj.getX;
print(getX());     // 42: called with global object as this


var boundGetX = getX.bind(obj); // this now fixed as obj
print(boundGetX()); // 17: calls obj.getX with obj as this
</pre>
<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">// Creating a function that calls another function with pre-specified leading arguments
function List()
{
  var a = [];
  for (var i = 0; i &lt; arguments.length; i++)
    a.push(arguments[i]);
  return a;
}

var l1 = List(1, 2, 3); // [1, 2, 3]

var LeadingZeroList = List.bind(null /* this */, 0);

var l2 = LeadingZeroList(); // [0]
var l3 = LeadingZeroList(1); // [0, 1]
var l4 = LeadingZeroList(1, 2); // [0, 1, 2]
</pre>
<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">// Constructing with a bound function
function Point(x, y)
{
  this.x = x;
  this.y = y;
}
Point.prototype.toString = function() { return this.x + "," + this.y; };

print(new Point(1, 2)); // "1,2"

var thisObj = {};
var YAxisPoint = Point.bind(thisObj, 0 /* x */);

print(new YAxisPoint(5)); // "0,5": note thisObj is ignored

print(new YAxisPoint(17) instanceof Point);      // true
print(new YAxisPoint(17) instanceof YAxisPoint); // true again
print(new Point(17, 42) instanceof YAxisPoint);  // true as well (NOTE: this will be false in the partial implementation)
</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">// ...continuing from above

// Can still be called as a normal function (although usually this is undesired)
YAxisPoint(13);
print(thisObj.x + "," + thisObj.y); // "0,13"
</pre>
<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">// NB: This code will work with the partial implementation of
//     Function.prototype.bind given above.
if (!Function.prototype.construct)
{
  Function.prototype.construct = function(args)
  {
    var boundArgs = Array.prototype.concat.apply([null], args);
    var boundFun = this.bind.apply(this, boundArgs);
    return new boundFun();
  };
}

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

var p1 = [2, 4];
print(Point.construct(p1)); // "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>
<h3 name="See_also">See also</h3>
<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