我正在尝试学习 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
关键字而不是 constructor
。 super()
方法只能从类的 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/