## 在es6中,子类继承父类的方法需要使用super()来调用父类中的构造函数
示例
```
<script>
class str {
constructor(x, y) {
this.x = x;
this.y = y;
}
sing() {
console.log(this.x + this.y)
}
}
// 继承使用 extends 继承
class sg extends str {
constructor(x, y) {
super(x,y);// 调用了父类的构造函数
}
}
const ta = new sg(1,2);
ta.sing();
</script>
```
## 可以使用super来调用父类中的方法
示例
```
class father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sing() {
console.log(this.x + this.y)
return '我是爸爸'
}
}
class son extends father {
constructor(x, y) {
super(x,y);// 调用了父类的构造函数
}
sing() {
// return '我是儿子'
console.log(super.sing() + '的儿子') // 这样就直接调用父类的方法了
// super.sing() 就是调用父类中的普通函数sing()
}
}
const ta = new son(1,2);
ta.sing();
// 继承中的属性或者方法查找原则: 就近原则
// 继承中,如果实例化子类输出一个方法,先看子类有没有这个方法,如果有就会先执行子类的方法
// 继承中,如果子类里面没有,就去查找父类里面有没有这个方法,如果有,就执行父类的这个方法(就近原则)
```
## 子类继承父类的加法,同时扩展减法方法
// 利用super调用父类的构造函数
// super 必须在子类this前面调用
```
<script>
class father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sing() {
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;
}
substract() {
console.log(this.x - this.y)
}
}
const ta = new son(5,3);
ta.substract();
ta.sing();
</script>
```
## 在es6中类没有变量提升,所以必须先定义类,才能通过类实例化对象,类里面的公共属性和方法一定要加this
```
class father {
constructor(x, y) {
this.x = x;
this.y = y;
// this.sing();
this.btn = document.querySelector('button');
this.btn.onclick = this.sing; // 这边不是用this.sing(), 是因为不需要立即调用它
}
sing() {
console.log(this.x + this.y)
}
}
```