简单来说就是:子类可以继承父类的一些属性和方法。
语法:( extends 关键字 )
class Father{
//父类
}
class Son extends Father{
//通过 子类名 extends 父类名来继承父类的方法
}
例子: 下面的 Son 子类就继承了父类 Father 的 money 方法
class Father{
constructor(){
}
money(){
console.log("来自父类的财富:" + 100)
}
}
class Son extends Father{
//通过 子类名 extends 父类名来继承父类的方法
}
//这里实例化一个 Son 类,并储存到 son 变量。
let son = new Son()
//尝试执行继承自父类 money() 方法
son.money()
浏览器打印结果:
子类向父类传递参数中 this 的指向问题
错误展示
//父类
class Father{
constructor(x, y){
this.x = x
this.y = y
}
sum(){
const res = this.x + this.y
console.log("总和:" + )
}
}
//子类
class Son extends Father{
constructor(x, y){
this.x = x
this.y = y
}
}
//这里实例化一个 Son 类,传递两个参数,并储存到 res_son 变量。
let son = new Son(10, 20)
//尝试执行继承自父类 sum() 方法。
son.sum()
打印结果:
这里的错误写到了在 constructor 构造函数中使用 super 关键字。
**原因:**即使子类继承了父类,但是 this 的指向依旧是各自指向自己的。
**解决方法:**将子类的 this.x 和 this.y 使用 super(x, y) 替换,这样就代表我在子类的构造函数调用了父类的构造函数并且把值传递过去,那么父类就有这个两个值,我们再调用子类继承父的 sum() 方法就可以正常输入值的总和。
//父类
class Father{
constructor(x, y){
this.x = x
this.y = y
}
sum(){
const res = this.x + this.y
console.log("总和:" + res)
}
}
//子类
class Son extends Father{
constructor(x, y){
super(x, y)
}
}
//这里实例化一个 Son 类,传递两个参数,并储存到 res_son 变量。
let res_son = new Son(10, 20)
//尝试执行继承自父类 sum() 方法。
res_son.sum()
打印结果:
super 关键字
不使用 super 时调用子类也有和父类方法名一样的方法。
super 用于访问和调用父类上的函数。可以调用父类的构造函数,也可以调用父类的普通函数
class Father{
say(){
return '我是父类'
}
}
class Son extends Father{
say(){
console.log('我是子类')
}
}
let son = new Son()
//尝试调用子类和父类中名字一样的方法
son.say()
结果:
这里是就近原则,子类实例化输出了一个方法,会先看看自己有没有这个方法,如果有就用自己的,如果没有就去查找继承的父类有没有这个方法。
使用 super 调用子类继承至父类方法名一样的方法。
class Father{
say(){
//返回了一个字符串
return '我是父类'
}
}
class Son extends Father{
say(){
console.log('我是子类的log输出,我通过 super 调用了父类的 say() 方法:' + super.say())
}
}
let son = new Son()
son.say()
结果:
例子加强: 父类有一个加法方法,子类有一个减法方法。
class Father{
constructor(x, y){
this.x = x
this.y = y
}
sum(){
const res = this.x + this.y
console.log("父类加法:" + res)
}
}
//子类
class Son extends Father{
constructor(x, y){
//这里要尤其注意一下代码顺序,super() 必须在定义 this 属性之前使用。
//利用 super 调用父类的构造函数
super(x, y)
this.x = x
this.y = y
}
subtract(){
const res = this.x - this.y
console.log('子类减法:' + res)
}
}
//这里实例化一个 Son 类,传递两个参数,并储存到 res_son 变量。
let res_son = new Son(10, 20)
//尝试执行继承自子类的 subtract() 方法。
res_son.subtract()
//尝试执行继承自父类的 sum() 方法。
res_son.sum()
注意: super() 必须在定义 this 属性之前使用(必须先调用父类的构造方法,才能使用子类构造方法)。
总结:
- extends 关键字可以用来继承父类方法使用。
- super 关键字的主要作用就是调用父类函数,可以调用构造函数也可以调用普通函数。
- super 必须在定义 this 属性之前使用。