icyber-ghost icyber-ghost - 5 months ago 32
Node.js Question

calling super() on child classes javascript throw Error

I'm trying to learn ES2015 JavaScript classses, and I started the code like this:

file: 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();


file: package.json

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


by running:

$ npm run serve


but i got this:

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


What am I missing here?

Node version: 6.2.1

Answer

The reason is that you are using construct keyword instead of constructor. The super() method can be called only from constructor() of a class and nowhere else. That's why you are getting the error.

Also you don't need to assign Human class as a const and can directly use it after the class declaration

let Person = new Human();

For more details on ES6 class(es) refer: 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();