super是es6新出的关键字,可以当作函数使用,也可以当作对象使用
一、super当做函数使用
super当做函数使用时,super代表其父类的构造函数constructor,super()相当于Father.prototype.constructor.call(this)
class Father{constructor(){this.a = 1;}}class Son extends Father{constructor(){super();}}
二、super用作对象使用
2-1 普通方法中使用
super在普通方法中指向父类的原型对象
//super作为对象在普通方法中使用class Father {constructor() {this.a = 1;}//p函数是挂载到Father原型上的p() {console.log(thia.a);console.log('hello');}}class Son extends Father {constructor() {super();this.a = 2;super.p(); //'2 hello' Father.prototype.p()方法内部的this指向的是子类实例super.a; //undefined super无法访问Father的实例属性a,只可以访问其原型对象上的p}}
2-2 静态方法中使用
super在静态方法中指向父类
//super作为对象在静态方法中使用class Parent {static myMethod(msg) {console.log('static', msg);}myMethod(msg) {console.log('instance', msg);}}class Child extends Parent {static myMethod(msg) {super.myMethod(msg);//super指向父类因此访问的是static myMethod}myMethod(msg) {super.myMethod(msg);//super指向的是父类的原型,访问的是Parent.prototype.myMethod}}Child.myMethod(222);//static 222let child = new Child;child.myMethod(111);//instance 111
