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

Claude Pache claude.pache at gmail.com
Tue May 27 15:16:21 PDT 2014


This sounds good to me. Just a nit, you should define:

    Function.curryThis = function(f, base = undefined) {
        return function(...args) {
            return f.call(base, this, ...args);
        };
    };

so that you can do, e.g.,

    class ImprovedArray extends Array { /* _not_ overloading Array.from */ }
    var toImprovedArray = Function.curryThis(ImprovedArray.from, ImprovedArray)

without needing an extra `.bind`.

—Claude

Le 27 mai 2014 à 20:20, Nathan Wall <nathan.wall at live.com> a écrit :

> (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.
> 
> 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
>     Array.from(obj);
> 
>     // Proposal
>     var toArray = Function.curryThis(Array.from);
>     obj::toArray();
> 
> Another example:
> 
>     // ES5
>     Object.getOwnPropertyDescriptor(window.HTMLFormElement.prototype, 'elements').get;
> 
>     // Proposal
>     var getOwnPropertyDescriptor = Function.curryThis(Object.getOwnPropertyDescriptor);
>     window.HTMLFormElement.prototype::getOwnPropertyDescriptor('elements');
> 
> Perhaps sugar could be added to do both steps in one with another operator (say `:::`).
> 
>     // ES5
>     Object.getOwnPropertyDescriptor(window.HTMLFormElement.prototype, 'elements').get;
> 
>     // Proposal
>     window.HTMLFormElement.prototype:::Object.getOwnPropertyDescriptor('elements');
> 
> It's the same proposal as yours with slightly different syntax.  And I think the syntax makes some sense given a bind operator `::`.
> 
> [1] http://wiki.ecmascript.org/doku.php?id=strawman:bind_operator
> 
> 
> 
> Nathan
> 
> 
> 
> 		 	   		  



More information about the es-discuss mailing list