bind()


The JavaScript bind method has several uses. Typically, it is used to preserve execution context for a function that executes in another context. bind creates a new function that has the same body as the original function. The first argument passed to bind specifies the value of the this keyword in the bound function. You can also pass additional, optional argumentsto bind.

Bind has the same effect as .call(), but instead binds the function’s context prior to being invoked, this is essential to understand the difference. Using .bind() will not invoke the function, it just “sets it up”.

How bind is implemented


// If you’re interested to see what Function.prototype.bind() might look like 
// and what its doing internally, here is a very simple example:

Function.prototype.bind = function (scope) {
    var fn = this;
    return function () {
        return fn.apply(scope);
    };
}

How To Use bind

// The following code shows how to use the bind method.
// Define the original function.
var checkNumericRange = function (value) {
    if (typeof value !== 'number')
        return false;
    else
        return value >= this.minimum && value <= this.maximum;
}

// The range object will become the this value in the callback function.
var range = { minimum: 10, maximum: 20 };

// Bind the checkNumericRange function.
var boundCheckNumericRange = checkNumericRange.bind(range);

// Use the new function to check whether 12 is in the numeric range.
var result = boundCheckNumericRange (12);
document.write(result);
// Output: true
/*
In the following example, the thisArg object 
is different from the object 
that contains the original method.
Create an object that contains the original function.

*/

var originalObject = {
    minimum: 50,
    maximum: 100,
    checkNumericRange: function (value) {
        if (typeof value !== 'number')
            return false;
        else
            return value >= this.minimum && value <= this.maximum;
    }
}

// Check whether 10 is in the numeric range.
var result = originalObject.checkNumericRange(10);
document.write(result + " ");
// Output: false

// The range object supplies the range for the bound function.
var range = { minimum: 10, maximum: 20 };

/*
Create a new version of the checkNumericRange 
function that uses range.
*/

var boundObjectWithRange = originalObject.checkNumericRange.bind(range);

// Check whether 10 is in the numeric range.
var result = boundObjectWithRange(10);
document.write(result);
// Output: true
/* 
The following code shows how to use the 
arg1[,arg2[,argN]]] arguments. 
The bound function uses the parameters specified 
in the bind method as the first 
and second parameters. 

Any parameters specified when the bound function is called are used as the third, fourth (and so on) 
parameters.

*/

// Define the original function with four parameters.
var displayArgs = function (val1, val2, val3, val4) {
    document.write(val1 + " " + val2 + " " + val3 + " " + val4);
}

var emptyObject = {};

// Create a new function that uses the 12 and "a" parameters
// as the first and second parameters.
var displayArgs2 = displayArgs.bind(emptyObject, 12, "a");

// Call the new function. The "b" and "c" parameters are used
// as the third and fourth parameters.
displayArgs2("b", "c");
// Output: 12 a b c

Create Function Short Cut

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

results matching ""

    No results matching ""