js中 es6 class类的继承
语法
// 父类
class Father{
}
// 子类继承父类
class Son extends Father {
}
子类使用super关键字访问父类的方法
//定义了父类
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
//子元素继承父类
class Son extends Father {
constructor(x, y) {
//使用super调用了父类中的构造函数
super(x, y);
}
}
var son = new Son(10, 20);
son.sum(); //结果为30
注意:
- 继承中,如果实例化子类输出一个方法,先看子类有没有这个方法,如果有就先执行子类的
- 继承中,如果子类里面没有,就去查找父类有没有这个方法,如果有,就执行父类的这个方法(就近原则)
- 如果子类想要继承父类的方法,同时在自己内部扩展自己的方法,利用super 调用父类的构造函数,super 必须在子类this之前调用
<script>
// 父类有加法方法
class Father{
constructor(x,y) {
this.x = x ;
this.y = y ;
}
sum() {
console.log(this.x + this.y);
}
}
// 子类继承父类加法的方法, 同时 扩展减法方法
class Son extends Father {
constructor (x,y){
// 利用super调用父类的构造函数
// super必须在子类this之前调用
super(x,y);
this.x = x;
this.y = y;
}
subtract(){
console.log(this.x - this.y);
}
}
var son = new Son(20,10);
son.subtract();//10
son.sum(); //30
</script>
**注意:**this的指向问题,类里面的共有的属性和方法一定要加this使用.
- constructor中的this指向的是new出来的实例对象
- 自定义的方法,一般也指向的new出来的实例对象
- 绑定事件之后this指向的就是触发事件的事件源