https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super
super
是一个关键字,用来调用父类的方法。
调用方式有两种,super(...params)
,super.method(...params)
第一种方式super(...params)
,
(1)只能用于constructor
函数中,用于调用父类的constructor
,
(2)必须在this
被使用之前进行调用,
(3)子类constructor
函数中,必须调用super(...params)
第二种方式super.method(...params)
,
(1)可用于调用父类中的任何给定名字的函数,包括super.constructor(...params)
,
(2)可在任何子类函数中调用,
(3)static
函数只能调用父类的static
函数,实例函数只能调用父类的实例函数
class T1 {
constructor(...args) {
// can't call `super` in base-class constructor
}
static staticMethod1(...args) {
console.log(this, args);
}
instanceMethod1(...args) {
console.log(this, args);
}
}
class T2 extends T1 {
constructor(...args) {
// 1. can't use `this` before super call
// 2. must call `super(...args)` in sub-class constructor
// 3. call constructor with (this=T2's instance), and (params=args)
super(...args);
}
static staticMethod2(...args) {
// 1. can't call `super(...args)`
// 2. can only call static method in base-class, super.instanceMethod1===undefined
// 3. call staticMethod1 with (this=T2), and (params=args)
super.staticMethod1(...args);
}
instanceMethod2(...args) {
// 1. can't call `super(...args)`
// 2. can only call instance method in base-class, super.staticMethod1===undefined
// 3. call instanceMethod1 with (this=T2's instance), and (params=args)
super.instanceMethod1(...args);
}
}
let t2 = new T2(1, 2)
T2.staticMethod2(3, 4);
t2.instanceMethod2(5, 6);
注:
super.call
和super.apply
,实际上是在调用父类名为call
和apply
的方法。
如果父类没有定义同名方法,则值为undefined
。