Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1077430 of Function.prototype.bind()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Function/bind
  • Revision title: Function.prototype.bind()
  • Revision id: 1077430
  • Created:
  • Creator: maxehnert
  • Is current revision? No
  • Comment

Revision Content

{{JSRef}}

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

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 {{jsxref("Operators/new", "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 bound function (BF). A BF is an exotic function object (term from ECMAScript 6)  that wraps the original function object. Calling a BF generally results in the execution of its wrapped function.
A BF has the following internal properties:

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

When bound function is called, it calls internal method [[Call]] with following arguments Call(target, boundThis, args). Where, target is [[BoundTargetFunction]], boundThis is [[BoundThis]], args is [[BoundArguments]].

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.

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:

this.x = 9; 
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

Partially applied functions

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

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

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

With setTimeout

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

function LateBloomer() {
  this.petalCount = Math.ceil(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

Bound functions used as constructors

Warning: This section demonstrates JavaScript capabilities and documents some edge cases of the bind() method. The methods shown below are not the best way to do things and probably should not be used in any production environment.

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 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'

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

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

// 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 {{jsxref("Operators/new", "new")}}, or only by calling it, the target function must enforce that restriction.

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 {{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:

var slice = Array.prototype.slice;

// ...

slice.apply(arguments);

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

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

// ...

slice(arguments);

Polyfill

The bind function is an 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 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;
  };
}

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 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.
  • The partial implementation creates functions that do not have immutable "poison pill" {{jsxref("Function.caller", "caller")}} and arguments 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.)
  • The partial implementation creates functions that have a prototype property. (Proper bound functions have none.)
  • 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.

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
{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}} {{Spec2('ES5.1')}} Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-function.prototype.bind', 'Function.prototype.bind')}} {{Spec2('ES6')}}  
{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}} {{Spec2('ESDraft')}}  

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatChrome("7")}} {{CompatGeckoDesktop("2")}} {{CompatIE("9")}} {{CompatOpera("11.60")}} {{CompatSafari("5.1")}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatAndroid("4.0")}} {{CompatChrome("1")}} {{CompatGeckoMobile("2")}} {{CompatUnknown}} {{CompatOperaMobile("11.5")}} {{CompatSafari("6.0")}}

See also

  • {{jsxref("Function.prototype.apply()")}}
  • {{jsxref("Function.prototype.call()")}}
  • {{jsxref("Functions", "Functions", "", 1)}}

Revision Source

<div>{{JSRef}}</div>

<p>The <code><strong>bind()</strong></code> method creates a new function that, when called, has its <code>this</code> keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.</p>

<h2 id="Syntax">Syntax</h2>

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

<h3 id="Parameters">Parameters</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>

<h2 id="Description">Description</h2>

<p>The <strong>bind()</strong> function creates a new <strong>bound function</strong> <strong>(BF)</strong>. A&nbsp;<strong>BF</strong>&nbsp;is an <strong>exotic function object</strong> (term from <strong>ECMAScript 6</strong>)&nbsp; that wraps the&nbsp;original function object. Calling a <strong>BF</strong> generally results in the execution of its <strong>wrapped function</strong>.<br />
 A<strong> BF</strong>&nbsp;has the following internal properties:</p>

<ul>
 <li><strong>[[BoundTargetFunction]] </strong>- the wrapped function object;</li>
 <li><strong>[[BoundThis]]</strong> - the value that is always passed as the this value when calling the wrapped function.</li>
 <li><strong>[[BoundArguments]]</strong>&nbsp; - 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 this 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> with following arguments <strong>Call(<em>target</em>, <em>boundThis</em>, <em>args</em>).</strong> Where, <strong><em>target</em></strong> is<strong> [[BoundTargetFunction]]</strong>, <strong><em>boundThis </em></strong>is <strong>[[BoundThis]]</strong>, <em><strong>args </strong></em>is <strong>[[BoundArguments]]</strong>.</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 <code>this</code> value is ignored, while prepended arguments are provided to the emulated function.</p>

<h2 id="Examples">Examples</h2>

<h3 id="Creating_a_bound_function">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">
this.x = 9; 
var module = {
&nbsp; x: 81,
&nbsp; 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(undefined, 37);

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

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

<h3 id="With_setTimeout">With <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.ceil(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 use of a bound function only using&nbsp;{{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 <code>this</code> 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 <code>this</code> 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>The <code>bind</code> function is an 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 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>

<h2 id="Specifications">Specifications</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('ES6', '#sec-function.prototype.bind', 'Function.prototype.bind')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

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

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</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>{{CompatGeckoDesktop("2")}}</td>
   <td>{{CompatIE("9")}}</td>
   <td>{{CompatOpera("11.60")}}</td>
   <td>{{CompatSafari("5.1")}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</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>{{CompatGeckoMobile("2")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatOperaMobile("11.5")}}</td>
   <td>{{CompatSafari("6.0")}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also">See also</h2>

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