Classes with Static Arrow Functions

I am currently using the static land specification (an alternative to fantasy land). I want to not only use simple objects as types, but also ES2015 classes with static methods. I used these static methods as arrow functions in curry, instead of the usual functions. However, this is not possible in ES2015 classes:

class List extends Array { static map = f => xs => xs.map(x => f(x)) static of = x => [x] } 

My map does not need its own this , because it is just a curry function in the List constructor. To make it work, I have to write static map(f) { return xs => xs.map(x => f(x)) } , which is very annoying.

  • Why can't I use arrow functions with an assignment expression in ES2015 classes?
  • Is there a short way to achieve my goal anyway?
+7
javascript ecmascript-6 functional-programming arrow-functions
source share
1 answer

Why can't I use arrow functions with an assignment expression in ES2015 classes?

Because this is not how the syntax of the ES2015 class is developed - for now , see the line below.

Is there any short way to reach my goal?

Itโ€™s not clear to me that you want classes in general, just an object:

 const List = { map: f => xs => xs.map(x => f(x)), of: x => [x] }; 

(You said that extension is important for what you do.)

But if you want List extend Array (for example, you will have instances), but then add these statics to them, you will need two steps:

 class List extends Array { } Object.assign(List, { map: f => xs => xs.map(x => f(x)), of: x => [x] }); 

If you want them to be non-enumerable or non-configurable, etc., you need Object.defineProperties , not Object.assign ; I will leave this as an exercise for the reader ...


Here's a suggestion for stage 2 for class fields, including static fields. If he proceeds to step 4, he will eventually become part of the upcoming language specification (perhaps ES2018, it is unlikely at the moment you need to make ES2017, but you never know).

This will allow static fields to be declared inside the class, almost exactly as you showed them:

 // NOT IN THE LANGUAGE YET, BUT A PROPOSAL AT STAGE 2 class List extends Array { static map = f => xs => xs.map(x => f(x)); static of = x => [x]; } 

If you upgrade from Babel, you can say that it includes Stage 2 offers.

+11
source share

All Articles