具有静态箭头功能的类

时间:2016-08-22 12:49:25

标签: javascript functional-programming ecmascript-6 arrow-functions es6-class

我目前正在实施static land规范(幻想之地的另一种选择)。我不仅要使用普通对象作为类型,还要使用静态方法的ES2015类。我已经将这些静态方法实现为curry形式的箭头函数而不是普通函数。但是,ES2015类无法实现这一点:

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

我的map不需要自己的this,因为它只是List构造函数的curry函数。为了使它工作,我必须写static map(f) { return xs => xs.map(x => f(x)) },这是非常烦人的。

  • 为什么我不能在ES2015课程中使用箭头功能和赋值表达式?
  • 无论如何,有没有简洁的方法来实现我的目标?

1 个答案:

答案 0 :(得分:13)

  

为什么我不能在ES2015类中使用箭头函数和赋值表达式?

因为这不是ES2015类语法的设计方式 - 目前,请参阅以下行。

  

是否有简洁的方法来实现我的目标?

我不清楚你想要课程,只是一个对象:

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

(你已经说过扩展对你正在做的事情很重要。)

但是,如果您希望List扩展Array(例如,您将拥有实例),但随后将这些静态添加到其中,则需要两步:

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

console.log(List.of(42)); // [42]

如果您希望它们不可枚举或不可配置等,您需要Object.defineProperties而不是Object.assign;我将把它作为读者的练习......

类“字段”有一个Stage 3 proposal,包括静态字段,由JavaScript引擎构建器主动实现。 (现在你可以通过像Babel这样的工具来使用它。)它在类中提供静态字段声明语法,几乎就像你展示它们一样:

// Not in the language yet, but at Stage 3 and shipping without
// any flags in V8 (for instance, in Chrome)
class List extends Array {
  static map = f => xs => xs.map(x => f(x));
  static of = x => [x];
}

console.log(List.of(42)); // [42]

注意:有一种标准Array.of方法,因此我不会向of添加不兼容的List

最后,我应该注意,除非他们 有箭头函数,否则ES2015的class语法支持静态方法:

// ES2015+
class List extends Array {
  static map(f) {
    return xs => xs.map(x => f(x));
  }
  static of(x) {
    return [x];
  }
}

console.log(List.of(42)); // [42]