es6调用静态方法 [英] es6 call static methods
问题描述
调用静态方法的标准方法是什么?我可以想到使用构造函数
或使用类本身的名称,我不喜欢后者,因为它不觉得有必要。
What's the standard way to call static methods? I can think of using constructor
or using the name of the class itself, I don't like the latter since it doesn't feel necessary. Is the former the recommended way, or is there something else?
这是一个(设计的)示例:
Here's a (contrived) example:
class SomeObject {
constructor(n){
this.n = n;
}
static print(n){
console.log(n);
}
printN(){
this.constructor.print(this.n);
}
}
推荐答案
方法是可行的,但是当使用覆盖的静态方法进行继承时,它们做不同的事情。选择您期望的行为:
Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect:
class Super {
static whoami() {
return "Super";
}
lognameA() {
console.log(Super.whoami());
}
lognameB() {
console.log(this.constructor.whoami());
}
}
class Sub extends Super {
static whoami() {
return "Sub";
}
}
new Sub().lognameA(); // Super
new Sub().lognameB(); // Sub
通过类引用静态属性将实际上是静态的, 。使用 this.constructor
将使用动态分派并引用当前实例的类,其中静态属性可能具有继承的值,但可以也可以覆盖。
Referring to the static property via the class will be actually static and constantly give the same value. Using this.constructor
instead will use dynamic dispatch and refer to the class of the current instance, where the static property might have the inherited value but could also be overridden.
这与Python的行为相匹配,您可以通过类名或实例选择引用静态属性 self
。
This matches the behavior of Python, where you can choose to refer to static properties either via the class name or the instance self
.
如果希望静态属性不被覆盖(并始终引用当前类), like in Java ,使用显式引用。
If you expect static properties not to be overridden (and always refer to the one of the current class), like in Java, use the explicit reference.
这篇关于es6调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!