TOGOUTECH

javascript - 带有静态箭头函数的类

coder 2024-05-16 原文

我目前正在实现 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/

有关javascript - 带有静态箭头函数的类的更多相关文章

  1. javascript - 任何人都可以生成 opencv.js 吗? - 2

    我无法使用以下说明生成OpenCV.js:https://docs.opencv.org/master/d4/da1/tutorial_js_setup.html我有这个错误:CMakeError:CMakewasunabletofindabuildprogramcorrespondingto"UnixMakefiles".CMAKE_MAKE_PROGRAMisnotset.Youprobablyneedtoselectadifferentbuildtool.当我尝试执行时:python./platforms/js/build_js.pybuild_js好的,伙计们!

  2. javascript - "$attrs is readonly", "$listeners is readonly", "Avoid mutating a prop directly" - 2

    我是Vue新手。我正在尝试开发一个聊天应用程序,其中好友列表将显示在左侧菜单上,聊天框将显示在正文中。我正在使用ajax调用加载好友列表,并根据好友ID路由到聊天框。这是代码示例。<divclass="chat-containerclearfix"id="chat"><divclass="people-list"id="people-list"><chatlist-component></chatlist-component></div><divclass=

  3. javascript - 在 Angular 中导航时,将 child 路由到 parent 不起作用 - 2

    我使用的是angular5.1.0,路由系统有问题,让我解释一下:在我的应用程序路由模块中,我有一个url/api那个延迟加载另一个模块,在那个延迟加载的模块中我有下一个路由实现:api-routing.module.tsconstroutes:Routes=[{path:'',component:ApisComponent,data:{breadcrumbs:'APIs',},children:[{path:'',component:ApiListComponent,},{path:':id',component:Api

  4. javascript - Visual Studio -> Shared TypeScript Library -> TS6059 文件 '' 不在 'rootDir' '' 下。 'rootDir' 应该包含所有源文件 - 2

    我们正在使用VisualStudio2017并且有两个独立的Web项目,它们应该共享一些用TypeScript编写的React组件。还可以共享JavaScript文件和CSS文件。为此,我们在VisualStudio中创建了一个共享项目。WhatisthedifferencebetweenaSharedProjectandaClassLibraryinVisualStudio2015?目前该项目只有一个包含此信息的文件。exportconstTypes={Type1:'1',Type2:'2',Type3:'3'}为了测试,我可以像这样引

  5. javascript - Vue - 使用 refs 来聚焦元素目标 - 2

    点击spanclass="before-click"时,我想隐藏它,而是显示inputclass="after-click"。并且出现的输入标签必须是焦点!问题是当我尝试使用$refs.afterClick访问那个DOM并给它.focus()时,一个意外错误显示.focus()不是一个函数。如何解决这个问题?谢谢。varmyApp=newVue({el:'#app',data:{onEdit:false,msg:'Somethinginhere',},methods:{switchAndFocus(){if(!this.onEdit){this.onEd

  6. javascript - [Vue 警告] : Error in render function: "TypeError: Cannot read property ' first_name' of null" - 2

    我有以下Navigation.vue组件:<template><div>{{user.first_name}}</div></template><script>import{mapActions,mapGetters}from'vuex'exportdefault{name:'hello',methods:{...mapActions(['myAccount'])},mounted:function(){if(localStorage.getItem('access_to

  7. javascript - 基于javascript中的另一个数组过滤对象数组 - 2

    给定一个对象数组:people=[{id:"1",name:"abc",gender:"m",age:"15"},{id:"2",name:"a",gender:"m",age:"25"},{id:"3",name:"efg",gender:"f",age:"5"},{id:"4",name:"hjk",gender:"m",age:"35&

  8. javascript - Spring stomp websockets with vue.js - 2

    我正在尝试将Springwebsockets(STOMP)与Vue结合使用,但不知道该怎么做,甚至不知道该怎么做。我的websockets使用纯JS,但是当我尝试使用Vue时,我卡住了。这是我的Vue代码:varapp=newVue({el:'#app',data:{stompClient:null,gold:0},methods:{sendEvent:function(){this.stompClient.send("/app/hello",{},JSON.stringify({'name':$("#name").val

  9. javascript - ES6 双箭头参数(即 const update = x => y => { } ) - 2

    这个问题在这里已经有了答案:javascriptes6doublearrowfunctions(2个答案)关闭5年前。下面代码中的双箭头参数是什么意思?constupdate=x=>y=>{//Dosomethingwithxandy}与下面的相比有何不同?constupdate=(x,y)=>{//Dosomethingwithxandy}谢谢!

  10. javascript - 如果 JavaScript 是一种解释性语言,提升如何工作? - 2

    我对解释器的理解是它逐行执行程序,我们可以看到即时结果,不像编译语言那样转换代码,然后执行它。我的问题是,在Javascript中,解释器如何知道程序中某处声明了一个变量并将其记录为undefined?考虑下面的程序:functiondo_something(){console.log(bar);//undefined(butinmyunderstandingaboutaninterpreter,itshouldbethrowingerrorlikevariablenotdeclared)varbar=111;console.log(bar);//111}隐含理解为:functiond

随机推荐

  1. javascript - 任何人都可以生成 opencv.js 吗? - 2

    我无法使用以下说明生成OpenCV.js:https://docs.opencv.org/master/d4/da1/tutorial_js_setup.html我有这个错误:CMakeError:CMakewasunabletofindabuildprogramcorrespondingto"UnixMakefiles".CMAKE_MAKE_PROGRAMisnotset.Youprobablyneedtoselectadifferentbuildtool.当我尝试执行时:python./platforms/js/build_js.pybuild_js好的,伙计们!

  2. javascript - "$attrs is readonly", "$listeners is readonly", "Avoid mutating a prop directly" - 2

    我是Vue新手。我正在尝试开发一个聊天应用程序,其中好友列表将显示在左侧菜单上,聊天框将显示在正文中。我正在使用ajax调用加载好友列表,并根据好友ID路由到聊天框。这是代码示例。<divclass="chat-containerclearfix"id="chat"><divclass="people-list"id="people-list"><chatlist-component></chatlist-component></div><divclass=

  3. javascript - 在 Angular 中导航时,将 child 路由到 parent 不起作用 - 2

    我使用的是angular5.1.0,路由系统有问题,让我解释一下:在我的应用程序路由模块中,我有一个url/api那个延迟加载另一个模块,在那个延迟加载的模块中我有下一个路由实现:api-routing.module.tsconstroutes:Routes=[{path:'',component:ApisComponent,data:{breadcrumbs:'APIs',},children:[{path:'',component:ApiListComponent,},{path:':id',component:Api

  4. javascript - Visual Studio -> Shared TypeScript Library -> TS6059 文件 '' 不在 'rootDir' '' 下。 'rootDir' 应该包含所有源文件 - 2

    我们正在使用VisualStudio2017并且有两个独立的Web项目,它们应该共享一些用TypeScript编写的React组件。还可以共享JavaScript文件和CSS文件。为此,我们在VisualStudio中创建了一个共享项目。WhatisthedifferencebetweenaSharedProjectandaClassLibraryinVisualStudio2015?目前该项目只有一个包含此信息的文件。exportconstTypes={Type1:'1',Type2:'2',Type3:'3'}为了测试,我可以像这样引

  5. javascript - Vue - 使用 refs 来聚焦元素目标 - 2

    点击spanclass="before-click"时,我想隐藏它,而是显示inputclass="after-click"。并且出现的输入标签必须是焦点!问题是当我尝试使用$refs.afterClick访问那个DOM并给它.focus()时,一个意外错误显示.focus()不是一个函数。如何解决这个问题?谢谢。varmyApp=newVue({el:'#app',data:{onEdit:false,msg:'Somethinginhere',},methods:{switchAndFocus(){if(!this.onEdit){this.onEd

  6. javascript - [Vue 警告] : Error in render function: "TypeError: Cannot read property ' first_name' of null" - 2

    我有以下Navigation.vue组件:<template><div>{{user.first_name}}</div></template><script>import{mapActions,mapGetters}from'vuex'exportdefault{name:'hello',methods:{...mapActions(['myAccount'])},mounted:function(){if(localStorage.getItem('access_to

  7. javascript - 基于javascript中的另一个数组过滤对象数组 - 2

    给定一个对象数组:people=[{id:"1",name:"abc",gender:"m",age:"15"},{id:"2",name:"a",gender:"m",age:"25"},{id:"3",name:"efg",gender:"f",age:"5"},{id:"4",name:"hjk",gender:"m",age:"35&

  8. javascript - Spring stomp websockets with vue.js - 2

    我正在尝试将Springwebsockets(STOMP)与Vue结合使用,但不知道该怎么做,甚至不知道该怎么做。我的websockets使用纯JS,但是当我尝试使用Vue时,我卡住了。这是我的Vue代码:varapp=newVue({el:'#app',data:{stompClient:null,gold:0},methods:{sendEvent:function(){this.stompClient.send("/app/hello",{},JSON.stringify({'name':$("#name").val

  9. javascript - ES6 双箭头参数(即 const update = x => y => { } ) - 2

    这个问题在这里已经有了答案:javascriptes6doublearrowfunctions(2个答案)关闭5年前。下面代码中的双箭头参数是什么意思?constupdate=x=>y=>{//Dosomethingwithxandy}与下面的相比有何不同?constupdate=(x,y)=>{//Dosomethingwithxandy}谢谢!

  10. javascript - 如果 JavaScript 是一种解释性语言,提升如何工作? - 2

    我对解释器的理解是它逐行执行程序,我们可以看到即时结果,不像编译语言那样转换代码,然后执行它。我的问题是,在Javascript中,解释器如何知道程序中某处声明了一个变量并将其记录为undefined?考虑下面的程序:functiondo_something(){console.log(bar);//undefined(butinmyunderstandingaboutaninterpreter,itshouldbethrowingerrorlikevariablenotdeclared)varbar=111;console.log(bar);//111}隐含理解为:functiond