super这个关键字,既可以当作函数使用,也可以当作对象使用。当作函数使用时,super代表父类的构造函数,并在子类中执行Parent.apply(this),从而将父类实例对象的属性和方法,添加到子类的this上面。以下三点需要特别注意:
1、子类必须在constructor方法中调用super方法,如果子类没有定义constructor方法,constructor方法以及其内部的super方法会被默认添加。
测试代码:
class A {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
}
class B extends A {}
var b = new B("Tom", 20);
console.log(b.name);
console.log(b.age);
console.log(b.getName());
console.log(b.hasOwnProperty("name"));
//输出:Tom,20,Tom,true
2、在子类的constructor方法中,只有调用super之后,才可以使用this关键字,否则会报错。
测试代码:
class A {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
class B extends A {
constructor(name, age) {
this.job = "IT";
super(name, age);
}
}
var b = new B("Tom", 20)
//输出:报错
3、super()只能用在子类的constructor方法之中,用在其他地方就会报错。
测试代码:
class A {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
class B extends A {
toStr(name, age) {
super(name, age)
}
}
var b = new B("Tom", 20)
//输出:报错
super作为对象时,在子类中指向父类的原型对象。
即super=Parent.prototype。
测试代码:
class A {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
console.log(this.name);
}
}
A.prototype.n = 2;
class B extends A {
constructor(name, age) {
super(name, age);
}
toStr() {
return super.n;
}
activeGetName() {
super.getName();
}
}
var b = new B("Tom", 20);
console.log(b.toStr());
console.log(b.activeGetName());
//输出:2,Tom