继承:子类可以继承父类的一些属性和方法
extends关键字表示实现子类继承父类的属性和方法;
super关键字用于访问和调用对象父类上的函数,可以调用父类的构造函数,也可以调用父类的普通函数;
let that
let _that
class Father { // 父类
constructor (x, y) {
this.x = x
this.y = y
this.say() // father
}
sum() {
console.log(this.x + this.y)
}
say() {
return 'father'
}
}
class Son extends Father { // 子类继承父类
constructor (x, y) {
super(x, y) // 调用父类的构造函数,必须先调用父类构造方法再使用子类构造方法
this.x = x
this.y = y
that = this
}
say() {
super.say() // 调用父类的普通函数
}
substract() {
_that = this // this指向实例对象
console.log(this.y - this.x) // 子类继承父类加法的同时扩展减法方法
}
}
const son1 = new Son(1, 2)
son1.sum() // 3
son1.say() // father
son1.substract() // 1
console.log(that === son1) // true
console.log(_that === son1) // true
- 在ES6中类没有变量提升,所以必须先定义类,才能通过类实例化对象;
- 类里面的的共有属性和方法一定要加this使用;
- 类里面的this的指向问题,constructor里面的this指向创建的实例对象;