Arrow functions as methods

Irakli Gozalishvili rfobic at gmail.com
Tue Jul 10 15:02:16 PDT 2012


Hi,  

I just wanted to bring up IMO important limitation of arrow functions. They do solve unbound `this` issues when used as a callback, but they also introduce unfortunate limitation. Arrow functions can not really be
used as methods. For example it was great that in JS one could write a function that could be used as
a method or as function:

function map(f) {
  return this.reduce((result, value) =>  result.concat([ f(value) ]), [])
}

// Use as method
foo.map = map;
foo.map((x) => x + 1)

// Use as function
map.call(bar, (x) => x + 1)

I would say still is unfortunate that such reusable functions had do be called via special `.call` but never the less code sharing was simple to do.

Now arrow functions as they stand today can not be used in that manner as `this` refers to the outer scope `this` for a good reason. But it still would be nice to allow reusing them as methods, in fact they could be even solve current `map.call(…)`. What I'd like to propose is borrow successful idea from other languages and make:

foo.map((x) => x + 1)  

be a sugar for

map(foo, (x) => x + 1)

If `map` is an arrow function

That would make (arrow) functions a lot more composable:

var map = (list, f) =>
   list.reduce((result, value) => result.concat([ f(value) ]), [])

List.prototype.map = map

List().map((x) => x + 1)

or  

map(List(), (x) => x + 1)

or

map([ 1, 2, 3 ], (x) => x + 1)


I think this would make a good synergy of OO and functional styles in JS


Regards
--
Irakli Gozalishvili
Web: http://www.jeditoolkit.com/

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120710/836736c8/attachment-0001.html>


More information about the es-discuss mailing list