DEV Community

Ricardo Enrique
Ricardo Enrique

Posted on

All About Javascript Bind

The bind() method creates a new function, which when called, assigns its operator this the delivered value, with a sequence of arguments given preceding any given when the function is called.

The value of this is ignored when the function is called with the new operator.

Syntax

fun.bind(thisArg[, arg1[, arg2[, ...]]])
Enter fullscreen mode Exit fullscreen mode

Parameters

thisArg
It is a value that will be sent to the target function when the binding function is called. This value will be ignored if the binding function is constructed using the new operator.
arg1, arg2, ...

They are the arguments that will be sent in addition to those provided to the binding function when the target function is invoked.

The javascript bind function creates a new function (bound function) with the same body (internal call property in ECMAScript 5 terms) as the function to be called (the target function of the bound function) with the this reference associated to the first argument de bind (), which cannot be overwritten. bind () also accepts default parameters that will precede the rest of the specific parameters when the objective function is called. A bound function can also be constructed using the new operator: by doing so, it will act as if the objective function had been constructed instead.

In the latter case, the corresponding parameter for this will be ignored, although the default parameters that will precede the rest will be provided for the emulated function.

The simplest use of bind () is to make a function that, no matter how it is called, always points to the same object with the this reference. A common mistake for newer JavaScript programmers is that they get a reference to a method of an object, then they execute that method from the external reference and expect the reference to this to still point to the original object from which the method was obtained (e.g. when use that method in a callback). Without due care, the original item is commonly 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 getX = module.getX;
getX(); // 9, porque en este caso, "this" apunta al objeto global

// Crear una nueva función con 'this' asociado al objeto original 'module'
var boundGetX = getX.bind(module);
boundGetX(); // 81
Enter fullscreen mode Exit fullscreen mode

Top comments (0)