super关键字用于访问和调用父类上的构造函数,也可以调用父类的普通函数。
super必须在子类this之前调用
class Star{
constructor(name,age){
this.name=name;
this.age=age;
}
message(){
return "姓名:"+this.name+","+"年龄"+this.age
}
}
let test=new Star("lisa",23)
console.log(test.name); //lisa
console.log(test.message())//姓名:lisa,年龄23
class Father{
constructor(x,y){
this.x=x;
this.y=y
}
sum(){
console.log(this.x+this.y)
}
say(){
return "hello"
}
}
class Child extends Father{
constructor(x,y){
//利用super调用父类的构造函数
super(x,y)
this.x=x;
this.y=y;
}
sub(){
console.log(this.x-this.y)
}
hello(){
console.log(super.say())//调用父类的普通函数
}
}
let test1=new Child(11,2)
test1.sum();//13
test1.sub();//9
test1.hello();//hello
注意:1.类没有变量提升,所以先有类才能实例化
2.类里面共有的属性和方法必须要加this使用
3.constructor中的this指向实例对象,方法里面的this指向这个方法的调用者