10 javascript functional-programming ecmascript-6 arrow-functions es6-class
我目前正在实施静态土地规范(幻想土地的另一种选择).我不仅要使用普通对象作为类型,还要使用静态方法的ES2015类.我已经将这些静态方法实现为curry形式的箭头函数而不是普通函数.但是,ES2015类无法实现这一点:
class List extends Array {
static map = f => xs => xs.map(x => f(x))
static of = x => [x]
}
Run Code Online (Sandbox Code Playgroud)
我map不需要它自己this,因为它只是List构造函数的curry函数.为了使它工作,我必须写static map(f) { return xs => xs.map(x => f(x)) },什么是非常烦人的.
T.J*_*der 13
为什么我不能在ES2015类中使用箭头函数和赋值表达式?
因为这不是ES2015类语法的设计方式 - 现在,请参阅下面的行.
有没有简洁的方法来实现我的目标?
我不清楚你想要课程,只是一个对象:
const List = {
map: f => xs => xs.map(x => f(x)),
of: x => [x]
};
Run Code Online (Sandbox Code Playgroud)
(你已经说过扩展对你正在做的事情很重要.)
但是如果你想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]Run Code Online (Sandbox Code Playgroud)
如果你想要它们是不可枚举的或不可配置的等等,你需要Object.defineProperties而不是Object.assign; 我会把它作为读者的练习......
类"字段" 的第2阶段提议,包括静态字段.如果它进展到第4阶段,最终它将成为即将推出的语言规范的一部分(也许是ES2018;此时不太可能制作ES2017,但你永远不知道).
它将允许在类中声明的静态字段,几乎与您显示它们的方式完全相同:
// 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]Run Code Online (Sandbox Code Playgroud)
如果您使用Babel进行转换,则可以告诉它包含第2阶段提案.