总结一下类的继承吧,这块很重要
所谓继承,就是子类可以继承父类的一些属性和方法
举个例子
class Father{
constructor(){
}
money(){
console.log(100)
}
}
class Son extends Father{
}
let son = new Son()
son.money()
先定义一个父类Father,给父类里面加一个money方法,接下来再定义一个Son子类继承父类的属性和方法,通过给子类new一个实例,就可以直接使用父类里面的方法了
再来看一下下面这个,你猜能不能console.log出来呢??
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){
this.x = x
this.y = y
}
}
let son = new Son(1,2)
son.sum()
答案肯定是报错的
首先,我们子类确实可以使用父类sum方法,但是父类里面的this指向是父类constructor里面的数据,而下面的new Son里面的参数是传给了子类的constructor,所以父类里面没有得到1,2这两个数值,那么解决方法是什么呢?
下面就要说一下super关键字了,子类在constructor中使用super,必须放到this前面(必须先调用父类的构造方法,在使用子类构造方法)
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(x,y). //这样改动一下
}
}
let son = new Son(1,2)
son.sum()
另外继承,如果实例化子类需要一个方法,它会先从自身查找看有没有这个方法,然后再去父类查找,就是就近原则