js从类中调用静态方法 [英] js call static method from class
问题描述
我有一个带静态方法的类:
I have a class with a static method:
class User {
constructor() {
User.staticMethod();
}
static staticMethod() {}
}
对于静态方法是否有这样的东西(即引用没有实例的当前类)。
Is there something like this so for static methods (i.e. refer to the current class without an instance).
this.staticMethod()
所以我不必写类名'User'。
so I don't have to write the class name 'User'.
推荐答案
来自MDN文档
静态方法调用直接在类上进行,并且不能在类的实例上调用
。静态方法通常用于
创建实用程序函数。
Static method calls are made directly on the class and are not callable on instances of the class. Static methods are often used to create utility functions.
有关详细信息,请参阅=> https://developer.mozilla.org/en-US/docs/Web/JavaScript/参考/类/静态
For more please see=> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static
你可以这样做=> this.constructor.staticMethod());
调用静态方法。
You can do something like this => this.constructor.staticMethod());
to call static method.
class StaticMethodCall {
constructor() {
console.log(StaticMethodCall.staticMethod());
// 'static method has been called.'
console.log(this.constructor.staticMethod());
// 'static method has been called.'
}
static staticMethod() {
return 'static method has been called.';
}
}
这篇关于js从类中调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!