node.js - 函数或类之外的“ super ”

标签 node.js babeljs

我无法转换这小段代码:

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 环境。

具体来说:

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

关于node.js - 函数或类之外的“ super ”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34290753/

相关文章:

javascript - 与 fs 和 bluebird 的 promise

javascript - nodejs 错误是发送后无法设置 header

javascript - React 应用程序编译但控制台中出现错误

javascript - 我如何将 babel-polyfill 用于多个单独的条目/输出?

javascript - Babel 文件被复制而不被转换

unit-testing - 如何使用 JSDom 对 Jest 中的自定义元素执行单元测试

javascript - 循环中的 NodeJS MySQL 查询在预期之前返回

javascript - 对 Node.js 的 async.parallel() 的调用是同步的吗?

mysql - 在 Node 循环中选择和插入未按预期工作

javascript - Webpack require 方法返回意外的对象