Over a million developers have joined DZone.

Uncurrying 'this' in JavaScript

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

This post explains applications of uncurrying and currying this in JavaScript. It has been triggered by a tweet of Brendan Eich’s.

To understand what uncurrying this is and why it is useful, we first need to look at generic methods.

Generic methods

Normally, a method is very closely tied to its type: You can only use it on an object if the object is an instance of the method’s type. However, some methods are so useful that it would be nice if we could apply them to instances of other types, too. For example:
    // Simplified version of the actual implementation:
    Array.prototype.forEach = function (callback) {
        for(var i=0; i<this.length; i++) {
            if (i in this) {
                callback(this[i], i);
            }
        }
    };
this can be considered an implicit parameter of forEach(). forEach() works with any this parameter that can perform the following tasks.
  • length property: this.length
  • Property access: this[i]
  • Checking for the existence of a property: i in this
The arguments object (holding the actual parameters of a function) is not an instance of Array and thus cannot directly use forEach(). But it can do all of the above mentioned things. In order to apply forEach() to it, we only need to make this an explicit parameter (instead of an implicit one). Fortunately, functions have a call() method that lets us do that:
    function printArgs() {
        Array.prototype.forEach.call(arguments, function (elem, index) {
            console.log(index+". "+elem);
        });
    }
forEach.call() has one more argument than forEach(): Its first argument is the value of this. Interaction:
    > printArgs("a", "b")
    0. a
    1. b
There are several methods in JavaScript that are generic in this manner, most of them are in Array.prototype.

Uncurrying this

Uncurrying this in a method means going from a signature
    obj.method(arg1, arg2)
to a signature
    method(obj, arg1, arg2)
Uncurrying allows you to make a method prettier when it is applied generically. Example:
    Array.forEach = Array.prototype.forEach.uncurryThis();
    function printArgs() {
        Array.forEach(arguments, function (elem, index) {
            console.log(index+". "+elem);
        });
    }
There is a proposal for doing this for all Array methods in a future version of ECMAScript. The following are three ways of implementing uncurryThis.

Version 1: What is really happening [by Eich, slightly modified]?

    Function.prototype.uncurryThis = function () {
        var f = this;
        return function () {
            var a = arguments;
            return f.apply(a[0], [].slice.call(a, 1));
        };
    };
Version 2: The uncurried version of a function is the same as invoking the call() method on the original. We can borrow that method via bind():
    Function.prototype.uncurryThis = function () {
        return this.call.bind(this);
    };
Version 3: It is best to define standard methods without depending too much on external methods. Furthermore, bind() does not exist prior to ECMAScript 5. We thus rewrite version 2 as follows.
    Function.prototype.uncurryThis = function () {
        var f = this;
        return function () {
            return f.call.apply(f, arguments)
        };
    };
The above code is still in the vein of “borrowing the call() method”.

Currying this

The inverse of uncurryThis(), which is called curryThis(), is useful whenever a method wants to pass its this to a nested function. Instead of writing
    var obj = {
        method: function (arg) {
            var self = this; // let nested function access `this`
            someFunction(..., function() {
                self.otherMethod(arg);
            });
        },
        otherMethod: function (arg) { ... }
    }
you can write
    var obj = {
        method: function (self, arg) { // additional argument `self`
            someFunction(..., function() {
                self.otherMethod(arg);
            });
        }.curryThis(), // introduce an additional argument
        otherMethod: function (arg) { ... }
    }
We have turned the implicit parameter this into the explicit parameter self. In other words: we have gone from a dynamic this to a lexical self. JavaScript would be simpler if this was always an explicit parameter.

Implementing curryThis():

    Function.prototype.curryThis = function () {
        var f = this;
        return function () {
            var a = Array.prototype.slice(arguments);
            a.unshift(this);
            return f.apply(null, a);
        };
    };

 

From http://www.2ality.com/2011/11/uncurrying-this.html

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}