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

Jasper St. Pierre jstpierre at mecheye.net
Tue May 27 11:28:05 PDT 2014


I'm not sure I like it. Given how other languages use the "::" operator,
I'd expect "Foo::bar" to do some sort of static property lookup for a name
called "bar" on "Foo", not bind the local variable "Foo" to the local
variable "bar". I think "bar.bind(Foo)" is more than enough. I am OK with
your "curryThis" function, though, even if I think it's a bit too fancy for
any code I'd write.


On Tue, May 27, 2014 at 2:20 PM, Nathan Wall <nathan.wall at live.com> wrote:

> (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
>
>
>
>




-- 
  Jasper
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140527/46431647/attachment.html>


More information about the es-discuss mailing list