Bind

Example 1:

var log = console.log;
log("Hello"); -> TypeError as we lose the context. 

We could do:
log.call(console, "Hello"); 

But we don't want every single time we call 'call'. 
I want the variable 'log' to be bound to the 'console' object:

var log = console.log.bind(console);
log("hello");

Example 2:

function myFunction(one, two){
    console.log(arguments); -> Will appear in the arguments object
}

myFunction("one","two", 23423,234); 

function myBind(func, thisArg){
    return function(){
       func.apply(thisArg, arguments); 
       //With apply -> console.log(argument[0], argument[1])...etc
       //With call -> console.log(arguments); 
    };
}

var log = myBind(console.log, console);
log("Hello, World", "Rick" );

Example 3:

Currying - Ability to take a function, partially fill the argument list and then get back a new function that has those parameter pre filled in.

function add(left, right){
    return left + right;
}

//Let say we want to add '5' to each element in the array and get a new array. 
var array = [1,2,3,4,5,6]
console.log(array.map(function(item){
    return item + 5; //Output: [6,7,8,9,10,11]
}));

//But we can do the same with bind: 
console.log(array.map(add.bind(null,5))); //Output: [6,7,8,9,10,11]

The 'bind' function takes in additional arguments, similar to call. 

var add5 = add.bind(undefined, 5); //We now have a new function with the first parameter already applied. 
console.log(add5(10)); -> 15

results matching ""

    No results matching ""