Super方法用来调用和访问父类的方法
super 关键词可以单独出现在子类的构造函数中,调用父类的构造函数为子类属性赋值(注意super关键词必须出现在this关键词之前)。
class Father{
constructor(x, y){
this.x = x;
this.y = y;
this.name = 'Father'
}
sayName(){
console.log(this.name)
}
}
class Child extends Father{
constructor(x, y){
super(x, y);
this.name = 'Child';
}
sayPosition(){
console.log(`x:${this.x},y:${this.y}`);
}
}
new Child(5,10).sayPosition(); // x:5,y:10
super 方法还可以调用父类的函数
class Father{
constructor(x, y){
this.x = x;
this.y = y;
this.name = 'Father'
}
sayName(){
console.log(this.name)
}
}
class Child extends Father{
constructor(x, y){
super(x, y);
this.name = 'Child';
}
sayName(){
super.sayName();
}
}
new Child().sayName(); // Child
super 只能访问父类的方法,不能直接访问属性,访问属性需要使用 super.constructor.Property
class Father{
constructor(x, y){
this.x = x;
this.y = y;
this.name = 'Father'
}
}
class Child extends Father{
constructor(x, y){
super(x, y);
this.name = 'Child';
}
test(){
console.log(super.name,super.constructor.name); // 试试是否能访问父类的属性
}
}
new Child().test(); // undefined,"Father"
我们知道在类中访问自身的静态方法分为两种
1.在一个静态方法中直接使用 this.staticMethod
来访问另一个静态方法
2.在非静态方法中使用 CLASS.staticMethod
或者是this.constructor.staticMethod
来访问静态方法
class Father{
constructor(x, y){
this.x = x;
this.y = y;
this.name = 'Father'
}
static ping(){
return 'ping';
}
static bing(){
// 静态方法中直接使用 this.staticMethod 来访问
console.log(`bing,${this.ping()}`);
}
unStatic(){
// 非静态方法中使用 this.constructor.staticMethod 来访问
console.log(this.constructor.ping());
}
}
Father.bing(); // bing,ping
new Father().unStatic();// ping
在子类中访问父类的静态方法与此类似,
1.在子类静态方法中访问父类静态方法 super.FatherStaticMethod
2.在子类非静态方法中访问父类静态方法 super.constructor.FatherStaticMethod
当然,无论什么时候,使用Father.staticMethod
来访问静态方法都是可以的。
class Father{
constructor(x, y){
this.x = x;
this.y = y;
this.name = 'Father'
}
static ping(){
return 'ping';
}
}
class Child extends Father{
constructor(x, y){
super(x, y);
this.name = 'Child';
}
sayName(){
// 在子类的非静态方法中访问父类静态方法
console.log(super.constructor.ping());
}
static bing(){
// 在子类的静态方法中访问父类静态方法
console.log(`bing,${super.ping()}`);
}
}
new Child().sayName(); // ping
Child.bing(); // bing,ping