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.

Function.prototype.bind()

Este artigo necessita de uma revisão editorial. Como posso ajudar.

Esta tradução está incompleta. Ajude atraduzir este artigo.

O metodos bind() cria uma nova função que, quando chamada, tem o seu próprio this palavra-chave para o valor fornecido, com uma dada sequência dos argumentos que precedem um fornecido quando a nova função é chamada .

Syntax

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

Parámetros

thisArg
O valor a ser passado como este parâmetro para a função de destino quando a função vinculado é chamado. O valor é ignorado se a função ligada é construído usando o new operador.
arg1, arg2, ...
Argumentos para preceder argumentos fornecidos para vincular a função ao invocar a função de destino.

Descrição

A função bind() cria uma nova função (uma função vinculada)  com o mesmo corpo da função (internal call propriedade em ECMAScript 5 termos) como a função está sendo chamada ( a funções vinculadas função de destino) com o valor vinculado ao primeiro argumento para o método bind(),  que não pode ser sobrescrito. O método bind() também aceita levar argumentos padrão para fornecer para função de destino quando a função vinculada é chamada.

Exemplos

Criando uma função vinculada

O uso mais simples de bind () é fazer com que uma função que, não importa como é chamado, é chamado com um determinado this valor. Um erro comum para novos programadores JavaScript é extrair um método de um objeto, em seguida, chamar essa função e esperar que ele use o objeto original como este (por exemplo, usando esse método no callback-based code). Sem cuidados especiais, no entanto, o objecto original é normalmente perdido. Criando uma função vinculado a partir da função, usando o objeto original, perfeitamente resolve esse problema:

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

module.getX(); // 81

var getX = module.getX;
getX(); // 9,  porque, neste caso, "this" refere-se ao objeto global 

// Criando uma nova função com 'this' vinculada ao módulo
var boundGetX = getX.bind(module);
boundGetX(); // 81

Funções Parciais

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 window.setTimeout(), the this keyword will be set to the 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 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*/);
// not supported in the polyfill below,
// works fine with native bind:
var YAxisPoint = Point.bind(null, 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 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.

// 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 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 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 apply() function of Function.prototype, with the this value set to the slice() function of 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)));
        };

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

Specifications

Specification Status Comment
ECMAScript 5.1 (ECMA-262)
The definition of 'Function.prototype.bind' in that specification.
Standard Initial definition. Implemented in JavaScript 1.8.5.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Function.prototype.bind' in that specification.
Standard  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 7 4.0 (2) 9 11.60 5.1
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 4.0 1 4.0 (2) ? 11.5 6.0

See also

Etiquetas do documento e colaboradores

 Colaboradores desta página: fbctf, heronmedeiros, edvaldofarias
 Última atualização por: fbctf,