我有一个带有静态方法的类:
class User {
constructor() {
User.staticMethod();
}
static staticMethod() {}
}
静态方法是否有与此等效的方法(即引用没有实例的当前类)?
this.staticMethod()
所以我不必写类名:“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/Reference/Classes/static
你可以这样做 => this.constructor.staticMethod();
调用静态方法。
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.';
}
}
关于javascript - JS从类中调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43614131/