【问题标题】:calling super() on child classes javascript throw Error在子类上调用 super() javascript 抛出错误
【发布时间】:2016-10-12 18:23:40
【问题描述】:

我正在尝试学习 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 run serve

但我明白了:

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

我在这里错过了什么?

节点版本:6.2.1

【问题讨论】:

    标签: javascript node.js class ecmascript-6


    【解决方案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();

    【讨论】:

      【解决方案2】:

      构造函数的名称是constructor,而不是construct。请参阅MDN documentation

      因此,construct 被解释为普通方法。如错误所示,super只能在构造函数内部调用,不能在普通方法中调用。

      【讨论】:

        猜你喜欢
        • 2019-04-11
        • 2017-12-18
        • 1970-01-01
        • 2010-11-27
        • 2013-05-30
        • 2012-08-08
        • 2021-08-10
        • 1970-01-01
        • 2018-03-20
        相关资源
        最近更新 更多