DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Uncurrying 'this' in JavaScript

Uncurrying 'this' in JavaScript

Axel Rauschmayer user avatar by
Axel Rauschmayer
·
Nov. 03, 11 · Web Dev Zone · Interview
Like (0)
Save
Tweet
2.31K Views

Join the DZone community and get the full member experience.

Join For Free

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

JavaScript

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Most Popular Kubernetes Alternatives and Competitors
  • How to Submit a Post to DZone
  • Java Hashtable, HashMap, ConcurrentHashMap: Performance Impact
  • Password Authentication: How to Correctly Do It

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo