Function binding

Function binding is a procedure to keep the this context to the desired function when running another function. When a function is executed, the this object is attached to that particular function. The binding of function is useful in cases such as, callbacks and event handlers.

Function binding is applied through bind() method. The bind() method sets the this keyword to the provided value (function).

Example

Consider the example below where a handler function is called for the onload event. Typically when a document loads the alert should pop the "Function binding worked!!" message. But with the code below, “undefined” is shown. This is because the context of this.message is not saved to loadHandler in most browsers. It points to the window object.

<!DOCTYPE html>
<html>

<body>
    <script>
        var loadHandler = {
            message : "Function binding worked!!",
            
            handleLoad: function(){
                alert(this.message);
            }
        };    
    window.addEventListener("load",loadHandler.handleLoad);        
    </script>
</body>
    
</html>

Example of function binding (bind() method)

The problem from above is solved by ECMAScript bind() method where the context of “this” is set to the loadHandler.handleLoad().

Function currying

Function currying is also called partial function application. When a function has multiple arguments and all of them are readily not available, they are passed to the function as parts. It works similar to the function binding, where a closure is used to return new function.  But instead of context as in bind(), a set of arguments are passed in function currying.

In the example below, a message is constructed by currying. The function showMessage() expects two arguments. If no argument is passed, the function is simply returned. If one argument is passed, the argument is assigned to name. The code var fn = showMessage("Naveen"); stores the string “Naveen” in name and returns a function. When second string is passed to the function as fn("How are you Dude!!") the function(a) executes and the complete message is displayed. Closure is used here.

The line showMessage("Naveen")("How are you Dude!!"); is same as above, where the “Naveen” is passed as the first argument. When the second argument is passed to the returned function of the closure, the message is concatenated.

In showMessage("Naveen", "Coming to party?"); line of the code, both the arguments are passed, and else statement is executed where message is concatenated.

Example of function currying

 

›› go to examples ››