Syntactic sugar for using a function as if it were a method of its first argument

Nathan Wall nathan.wall at
Tue May 27 11:20:06 PDT 2014

(Sorry about the formatting in the last one. Trying again.)

I have a syntax proposal, but it goes along with a slightly different way of thinking of this.

The proposed bind operator[1] can take a function which acts as a method and make a call to it with a specific receiver without the receiver needing to have the method defined as a property (basically a nicer syntax for `call` and `apply`).  Given a bind operator, this problem reduces to just having a way to take a function and turn its first argument into its `this`.  So good syntax can be achieved in two steps.

1. Turn the function into a method.
2. Invoke with bind operator.

To solve step 1, we could have something like `Function.curryThis` which does the opposite of "uncurryThis":

    Function.curryThis = function(f) {
        return function(...args) {
            return f(this, ...args);

Example use:

    // ES5

    // Proposal
    var toArray = Function.curryThis(Array.from);

Another example:

    // ES5
    Object.getOwnPropertyDescriptor(window.HTMLFormElement.prototype, 'elements').get;

    // Proposal
    var getOwnPropertyDescriptor = Function.curryThis(Object.getOwnPropertyDescriptor);

Perhaps sugar could be added to do both steps in one with another operator (say `:::`).

    // ES5
    Object.getOwnPropertyDescriptor(window.HTMLFormElement.prototype, 'elements').get;

    // Proposal

It's the same proposal as yours with slightly different syntax.  And I think the syntax makes some sense given a bind operator `::`.




More information about the es-discuss mailing list