javascript - 我可以在没有 Babel 的 Node.js 中使用 ES6 Javascript 吗?
问题描述
我只是想知道,是否可以在 2019 年的 Node 10.15 中使用 ES6,因为我认为,ES6 现在将成为原生支持和实现的 Javascript 功能?我在这里找到了一些答案:NodeJS 计划支持导入/导出 es6 (es2015) 模块 ,但我不确定现在的实际状态。
我刚刚在 Node 中尝试了一些带有箭头函数的 ES6 类:
class Test {
testVar = 1;
constructor(x,y) {
this.counter =0;
this.x = x;
this.y = y;
this.increaseCounter();
this.testVar +=1;
}
getCounter = () => {
console.log("Counter:", this.counter);
}
increaseCounter = () => {
this.counter += 1;
}
}
我收到一个错误:
getCounter = () => {
^
SyntaxError: Unexpected token =
而且,我无法创建对类来说是全局的类实例变量(并且每次创建新的类实例时都会将 testVar 增加 1..)在 Javascript 类中通常是如何完成的?
我知道有一个 babel 编译器包支持这个并以某种方式转换代码,但是现在 ES6 不应该是原生支持的 Javascript 代码吗?
解决方案
我可以在没有 Babel 的 Node.js 中使用 ES6 Javascript 吗?
是的,你可以,Node 支持 ES2018 之前的所有 JS (ECMAScript) 功能: https ://node.green/
你应该像这样创建你的方法:
class Test {
testVar = 1;
constructor(x, y) {
this.counter = 0;
this.x = x;
this.y = y;
this.increaseCounter();
this.testVar += 1;
}
getCounter() {
console.log("Counter:", this.counter);
}
increaseCounter() {
this.counter += 1;
}
}
无需仅出于持有匿名箭头函数的目的而创建属性。
推荐阅读
- c# - 如何在具有复合键的模型的实体框架核心中获取单个实体?
- python - KFold 将拆分数量解压缩为相同数量的变量,而不是只有 2 个
- wordpress - 如何在 wordpress 主题中找到隐藏代码
- python - Python Pandas:如何更新 groupby 中其他列的值?
- c++ - std::is_class 在引用类上为假
- firebase - 为什么在 Firestore 中写入 1 个文档需要 +30 次读取?
- python - 如何在 Python Pandas 中将多行更改为单行
- go - 使用 jwt-go 库 - 密钥类型无效
- python - 如果键不存在,则将字典值映射到列表并返回原始值
- regex - 正则表达式确定图像文件是否从 Facebook 下载