问题描述
我一直在学习一些React,并且一直在使用ES6类编写基于类的组件。 我正在处理一个小的Node项目,但是此语法均无效。
class Handler {
handleReq = () => {
this.ctx = ctx;
};
testFunc = async () => {
};
}
export default (HandleReq = Handler.prototype.handleReq);
这种语法有什么问题?
它不在Node中运行吗?
我必须安装esm
才能使导入/导出语法正确运行,但是仍然无法编译。
1楼
Jonas Wilms
2
2019-03-02 19:48:07
仍处于建议阶段(已经处于第3阶段,因此它们将很快成为语言的一部分)。 这意味着某些运行时可能已经支持它们,但是还不需要。 用今天的提案可靠您必须用transpile下来 。
这会将您的代码转换为以下ES6:
class Handler {
constructor() {
this.handleReq = () => {
this.ctx = ctx;
};
this.testFunc = async () => {
};
}
}
因此,这些方法实际上仅存在于构造后的实例上,而不存在于Handler.prototype
。
2楼
helloitsjoe
0
2019-03-03 19:27:38
正如其他人指出的那样,如果不进行编译,则类字段还不是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;