Chr*_*ris 20 javascript static class this
我有一个静态方法的类:
class User {
constructor() {
User.staticMethod();
}
static staticMethod() {}
}
Run Code Online (Sandbox Code Playgroud)
对于静态方法是否有这样的东西(即引用没有实例的当前类).
this.staticMethod()
Run Code Online (Sandbox Code Playgroud)
所以我不必写类名'User'.
Nin*_*eer 35
来自MDN文档
静态方法调用直接在类上进行,并且在类的实例上不可调用.静态方法通常用于创建实用程序功能.
有关详细信息,请参阅=> 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.';
}
}
Run Code Online (Sandbox Code Playgroud)