javascript - 在子类上调用 super() javascript throw Error

标签 javascript node.js class ecmascript-6

我正在尝试学习 ES2015 JavaScript 类,我开始这样写代码:

文件:index.js

/* parent class */
class Thing {

 construct(){
    console.log("thing constructor");
 }

}

/* child class */
const Human =  class Human extends Thing {

 construct(){
   super();
 }

}


let Person = new Human();

文件:package.json

{
  "scripts": {
    "serve": "nodemon index.js --exec babel-node"
  },
  "dependencies": {
    "babel-cli": "^6.9.0",
    "babel-preset-es2015": "^6.9.0"
  }
}

通过运行: $ npm 运行服务

但我明白了:

   SyntaxError: index.js: super() outside of class constructor (14:3)
      12 | 
      13 |  construct(){
    > 14 |    super();
         |    ^
      15 |  }

我在这里错过了什么?

Node 版本:6.2.1

最佳答案

原因是您使用的是 construct 关键字而不是 constructorsuper() 方法只能从类的 constructor() 中调用,不能从其他任何地方调用。这就是您收到错误的原因。

而且你不需要将Human类赋值为const,可以在类声明后直接使用

let Person = new Human();

有关ES6 类 的更多详细信息,请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

class Thing {
  constructor(){
   console.log("thing constructor");
  }
}

/* child class */
class Human extends Thing {
  constructor(){
    super();
  }
}

let p = new Human();

关于javascript - 在子类上调用 super() javascript throw Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37771022/

相关文章:

node.js - 监控 Node.js 发送的请求 header

python - 如何覆盖类,或取消声明类或在 python 中重新声明类?

java - 创建一个不带 'new' 参数的构造函数

javascript - AngularJS - ng-bind 不更新

javascript - 如何在mapbox GL JS上按日期范围过滤数据?

node.js - AWS Lambda 可以与外部互联网服务通话吗?

javascript - Cypress Cucumber - 如何让我的步骤按顺序运行?

javascript - 禁用拖动图像或链接的重定向

javascript - textarea 是最适合显示/隐藏链接文本的 UI 元素,就像在 Google map 中一样吗?

c++ - 在模板类之外定义运算符重载