类中的继承和超集:
class Car {
constructor() {
console.log(“Creating a new car”);
}
}
class Porsche extends Car {
constructor() {
super();
console.log(“Creating Porsche”);
}
}
let c = new Porsche();
// Creating a new car
// Creating Porsche
extends 允许一个子类继承父类,需要注意的是,子类的 constructor 函数中需要执行 super() 函数。
当然,你也可以在子类方法中调用父类的方法,如 super.parentMethodName()。
有几点值得注意的是:
类的声明不会提升(hoisting),如果你要使用某个 Class,那你必须在使用之前定义它,否则会抛出一个 ReferenceError 的错误
在类中定义函数不需要使用 function 关键词
示例: