我无法转换这小段代码:
class FooBar extends SomeParent {
constructor() {
super();
}
start() {
var foo = function() {
super.start(); // <-- Error: 'super' outside of function or class
};
}
}
抛出的错误是函数或类之外的'super'
。
但是,相同的代码在 Babel REPL 中可以正常转换。 .
我正在使用此命令使用自定义 Node.JS 程序进行编译:
babel.transformFileSync(filename, { presets: [ 'es2015' ] } );
安装信息:
$ npm ls --global --depth 0
/usr/lib
├── babel@6.3.13
├── babel-core@6.3.17
├── babel-plugin-external-helpers-2@6.3.13
├── babel-plugin-syntax-async-functions@6.3.13
├── babel-plugin-transform-async-to-generator@6.3.13
├── babel-plugin-transform-regenerator@6.3.18
├── babel-plugin-transform-runtime@6.3.13
├── babel-polyfill@6.3.14
├── babel-preset-es2015@6.3.13
└── npm@1.4.28
$ node -v
v0.10.40
我做错了什么?使用 Babel 5 进行编译时没有问题...
最佳答案
它在 Babel REPL 中有效,因为我认为 Babel 5 没有对此进行检查。
这是无效的:
class Example extends Parent {
start() {
var foo = function() {
super.start();
};
}
}
但是使用箭头函数可以:
class Example extends Parent {
start() {
var foo = () => {
super.start();
};
}
}
因为 super
行为是基于其调用位置的 this
环境。虽然箭头函数与其父函数共享其 this
环境,但标准函数引入了一个整体 not this
环境。
具体来说:
关于node.js - 函数或类之外的“ super ”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34290753/