Uncurrying “this” in JavaScript

[2011-11-02] dev, javascript, advancedjs, jslang
(Ad, please don’t block)
Update 2011-12-17: New section “Making uncurryThis() safe to use in the presence of untrusted code”.

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

Uncurrying this

Uncurrying this means: Given a method with the signature
    obj.foo(arg1, arg2)
transform it into a function with the signature
    foo(obj, arg1, arg2)
To understand why that 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.

Use cases for uncurrying this

Use case: apply a method via map(). Array.prototype.map() allows you to apply a function to each element in array. But what if you instead want to invoke a method? Uncurrying this lets you do that:
    var toUpperCase = String.prototype.toUpperCase.uncurryThis();
    > [ "foo", "bar", "baz" ].map(toUpperCase)
    [ 'FOO', 'BAR', 'BAZ' ]

Use case: Turn a generic method into a function. Uncurrying this 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.

Implementing uncurryThis()

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”.

The inverse is useful, too – currying this

The inverse of uncurryThis(), is called curryThis(). It puts this into the first parameter of a function. You can thus write the following function
    function(self, arg) {
        return self.foo + arg;
    }
and currying this turns it into
    function(arg) {
        return this.foo + arg;
    }

Use case: letting a method 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.

The implementation. Implementing curryThis():

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

If you don’t want to extend built-ins

The two implementations presented here are added to the built-in Function. You can, however, easily rewrite them and turn them into stand-alone functions.
    function uncurryThis(f) {
        return function () {
            return f.call.apply(f, arguments)
        };
    }
    function curryThis(f) {
        return function () {
            var a = Array.prototype.slice.call(arguments);
            a.unshift(this);
            return f.apply(null, a);
        };
    }
Note that you have just manually uncurried this for these functions.

Making uncurryThis() safe to use in the presence of untrusted code

Mark Miller uses uncurryThis() as an example for “safe meta-programming”:
How does one write a JavaScript meta-program that can operate reliably on other objects in its JavaScript context (in a browser – within the same frame), despite the loading of arbitrary code later into that same frame? The problem is that the later code may arbitrarily modify, override, or remove methods on the primordial built-in objects. To make the problem tractable, we assume that the meta program consists of modules that are first evaluated before their frame has become corrupted.