在function或课堂之外的“超级”

我不能传译这一小段代码:

class FooBar extends SomeParent { constructor() { super(); } start() { var foo = function() { super.start(); // <-- Error: 'super' outside of function or class }; } } 

抛出的错误是'super' outside of function or class

但是,相同的代码在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 

我究竟做错了什么? 使用巴别塔5时,我没有任何问题

它在Babel REPL中起作用,因为Babel 5没有检查我想要的。

这是无效的:

 class Example extends Parent { start() { var foo = function() { super.start(); }; } } 

但是使用箭头function可以:

 class Example extends Parent { start() { var foo = () => { super.start(); }; } } 

因为super行为是基于其呼叫位置的this环境。 当一个箭头函数与它的父类共享它的this环境时,一个标准函数引入了一个整体而不是this环境。

特别:

  1. 12.3.5.1调用MakeSuperPropertyReference()
  2. GetThisEnvironment()调用GetThisEnvironment() ,在第一种情况下它将是函数expression式,而在箭头情况下将是类方法,然后在该环境中调用HasSuperBinding()
  3. 8.1.1.3.3将在第一种情况下返回false ,因为函数expression式没有[[HomeObject]]而类方法则是。