解决方案
刚刚找到解决方案,使用this
但不确定这是否正确,如有必要,请查看/更正。
class SuperClass {
static calc1() {
return 5;
}
static calc2() {
return 10;
}
static calcAll() {
//reference to this, bound to class itself, because of 'static'
return this.calc1() + this.calc2();
}
}
class SubClass extends SuperClass {
//override
static calc1() {
return 1000;
}
}
console.log(SuperClass.calcAll()); //5+10 = 15
console.log(SubClass.calcAll()); //1000+10 = 1010
可选信息:
顺便发现了一些东西
覆盖实例方法,是一样的:
class SuperClass {
calc1() {
return 5;
}
calc2() {
return 10;
}
calcAll() {
//reference to this, bound to instance
return this.calc1() + this.calc2();
}
}
class SubClass extends SuperClass {
//override
calc1() {
return 1000;
}
}
console.log(new SuperClass().calcAll()); //5+10 = 15
console.log(new SubClass().calcAll()); //1000+10 = 1010
要在实例方法中使用静态方法,或将静态方法映射到实例方法上,请使用当前构造函数引用。
class SuperClass {
static calc1() {
return 5;
}
calc2() {
return 10;
}
calcAll() {
//'this' bound to instance, and we get current! (e.g. SubClass) class, by .constructor call
return this.constructor.calc1() + this.calc2();
}
}
class SubClass extends SuperClass {
//override
static calc1() {
return 1000;
}
}
console.log(new SuperClass().calcAll()); //5+10 = 15
console.log(new SubClass().calcAll()); //1000+10 = 1010
将静态方法映射到实例方法:
class SuperClass {
static calc1(num) {
return num;
}
calc1(...args) {
//reference to static
return this.constructor.calc1.apply(this.constructor, args);
}
/* alternative:
calc1(num) {
//reference to static
return this.constructor.calc1(num);
}
*/
}
class SubClass extends SuperClass {
//override
static calc1(num) {
return num + 1000;
}
}
//call statics
console.log(SuperClass.calc1(5)); //5
console.log(SubClass.calc1(5)); //5+1000 = 1005
//call instance
console.log(new SuperClass().calc1(5)); //5
console.log(new SubClass().calc1(5)); //5+1000 = 1005