class讲解之9 继承
2020-08-11 本文已影响0人
zhang463291046
以下内容是引用或者借鉴别人的,自己只是做个笔记,方便学习。理解错误的地方,欢迎评论。如有侵权,私聊我删除,未经允许,不准作为商业用途
在类名ColorPoint后面通过extends关键字实现继承,继承Point类的所有(实例和静态,私有不能)属性和方法
class Point {
}
class ColorPoint extends Point {
}
子类没有定义constructor方法,这个方法会被默认添加,代码如下
class ColorPoint extends Point {
}
// 等同于
class ColorPoint extends Point {
constructor(...args) {
super(...args);
}
}
子类ColorPoint中显式定义构造方法constructor,必须调用super()方法,否则报错。只有调用super()方法之后,才可以在其后使用this关键字,否则报错。super()方法只能用在子类的构造函数之中,否则报错。
class Point {
}
class ColorPoint extends Point {
constructor() {
this.color = 'green'; // ReferenceError
}
m() {
super(); // ReferenceError
}
}
let cp = new ColorPoint(); // ReferenceError