当前位置: 代码迷 >> JavaScript >> Node中的ES6类和函数用法
  详细解决方案

Node中的ES6类和函数用法

热度:48   发布时间:2023-06-05 14:22:50.0

我一直在学习一些React,并且一直在使用ES6类编写基于类的组件。 我正在处理一个小的Node项目,但是此语法均无效。

class Handler {
  handleReq = () => {
    this.ctx = ctx;
  };

  testFunc = async () => {

  };
}

export default (HandleReq = Handler.prototype.handleReq);

这种语法有什么问题? 它不在Node中运行吗? 我必须安装esm才能使导入/导出语法正确运行,但是仍然无法编译。

仍处于建议阶段(已经处于第3阶段,因此它们将很快成为语言的一部分)。 这意味着某些运行时可能已经支持它们,但是还不需要。 用今天的提案可靠您必须用transpile下来 。

这会将您的代码转换为以下ES6:

 class Handler {
  constructor() {
    this.handleReq = () => {
      this.ctx = ctx;
    };

    this.testFunc = async () => {
    };
   }
 }

因此,这些方法实际上仅存在于构造后的实例上,而不存在于Handler.prototype

正如其他人指出的那样,如果不进行编译,则类字段还不是ES6语法的一部分。 如果要避免构建步骤,则等效节点语法为:

// import someImport from './some-import' is invalid, instead use:
const someImport = require('./some-import');

class Handler {
  constructor() {
    this.handleReq = this.handleReq.bind(this);
    this.testFunc = this.testFunc.bind(this);
  }

  handleReq() {
    this.ctx = ctx; // Where is ctx coming from?
  }

  async testFunc() {

  }
}

// export default Handler.prototype.handleReq is invalid, instead use:
module.exports = Handler.prototype.handleReq;
  相关解决方案