为什么我不能在 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
; 我将把它作为练习留给读者......
有一个关于类“字段”的第 3 阶段提案,包括静态字段,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]