Javascript ES6 类型错误 : Class constructor Client cannot be invoked without 'new'

标签 javascript node.js ecmascript-6 syntax-error

我有一个用 Javascript ES6 编写的类。当我尝试执行 nodemon 命令时,我总是看到此错误 TypeError: Class constructor Client cannot be invoked without 'new'

下面提到了完整的错误:

/Users/akshaysood/Blockchain/fabricSDK/dist/application/Transaction.js:45
        return (0, _possibleConstructorReturn3.default)(this, (FBClient.__proto__ || (0, _getPrototypeOf2.default)(FBClient)).call(this, props));
                                                                                                                              ^

TypeError: Class constructor Client cannot be invoked without 'new'
    at new FBClient (/Users/akshaysood/Blockchain/fabricSDK/dist/application/Transaction.js:45:127)
    at Object.<anonymous> (/Users/akshaysood/Blockchain/fabricSDK/dist/application/Transaction.js:195:14)
    at Module._compile (module.js:641:30)
    at Object.Module._extensions..js (module.js:652:10)
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)
    at Module.require (module.js:585:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/akshaysood/Blockchain/fabricSDK/dist/routes/users.js:11:20)

我想做的是,我创建了一个类,然后创建了该类的一个实例。然后我尝试导出该变量。

类结构定义如下:

class FBClient extends FabricClient{

    constructor(props){
        super(props);
    }

<<< FUNCTIONS >>>

}

我如何尝试导出变量 ->

var client = new FBClient();
client.loadFromConfig(config);

export default client = client;

您可以在这里找到完整的代码 --> Link . Babel 生成的代码 --> Link .

最佳答案

问题在于该类扩展了原生 ES6 类,并使用 Babel 转译为 ES5。转译类不能扩展原生类,至少在没有额外措施的情况下是这样。

class TranspiledFoo extends NativeBar {
  constructor() {
    super();
  }
}

结果类似

function TranspiledFoo() {
  var _this = NativeBar.call(this) || this;
  return _this;
}
// prototypically inherit from NativeBar 

因为 ES6 类应该只用 new 调用,NativeBar.call 会导致错误。

任何最新的 Node 版本都支持 ES6 类,它们不应被转译。 es2015 应该从 Babel 配置中排除,最好使用 env preset set to node target .

同样的问题applies to TypeScript .编译器应正确配置为不转译类,以便它们从 native 或 Babel 类继承。

关于Javascript ES6 类型错误 : Class constructor Client cannot be invoked without 'new' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51860043/

相关文章:

javascript - 在客户端的浏览器中解压缩内容

javascript - 无法使用 jest.each 运行测试

javascript - Express.js 与 i18n-node 的多语言

node.js - ZINTERSTORE 与 node_redis 的动态参数

javascript - 如何在内联 &lt;script&gt; 中访问捆绑的 ES6 类

javascript - 过滤器 es6 接受函数作为条件

asp.net - 如何将JavaScript变量的值分配给隐藏字段

JavaScript 对象文字尾随 "Dummy"对

node.js - 在 sailsjs 中指定路线

javascript - 在 JavaScript ES6 中,for-in 循环和 for-of 循​​环中,变量 i 在 block 的每次迭代后不再存在?