我目前正在实现 static land规范(幻想世界的另一种选择)。我不仅想使用普通对象作为类型,还想使用带有静态方法的 ES2015 类。我已经将这些静态方法实现为柯里化(Currying)形式的箭头函数,而不是普通函数。然而,这对于 ES2015 类是不可能的:
class List extends Array {
static map = f => xs => xs.map(x => f(x))
static of = x => [x]
}
我的 map
不需要它自己的 this
,因为它只是 List
构造函数上的柯里化(Currying)函数。为了让它工作,我必须编写 static map(f) { return xs => xs.map(x => f(x)) }
,这很烦人。
- 为什么我不能在 ES2015 类中使用箭头函数和赋值表达式?
- 有没有一种简洁的方法可以实现我的目标?
最佳答案
Why can't I use arrow functions along with an assignment expression in ES2015 classes?
因为那不是 ES2015 类语法的设计方式——暂时,请参阅下面的行。
Is there a concise way to achieve my goal anyway?
我不清楚你想要类,只是一个对象:
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
方法,因此我不会向该 List
添加不兼容的 of
。
最后,我要指出,除非有某种原因必须是箭头函数,否则 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]
关于javascript - 带有静态箭头函数的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39080040/