我有一个带有静态方法的类:
class User {
constructor() {
User.staticMethod();
}
static staticMethod() {}
}对于静态方法(例如,引用没有实例的当前类),是否存在与此等效的方法?
this.staticMethod()所以我不需要写类名:"User“。
发布于 2017-04-25 14:56:31
来自MDN文档
静态方法调用直接在类上进行,不能在类的实例上调用。静态方法通常用于创建实用程序函数。
欲了解更多信息,请访问see=> 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.';
}
}发布于 2017-10-11 17:23:53
您可以使用:User.staticMethod()而不是:this.constructor.staticMethod()
发布于 2017-04-25 14:56:27
static事物绑定到类而不是实例。因此,您至少必须指定类名。
如果您不想将它们绑定到类,则使它们成为全局的。
https://stackoverflow.com/questions/43614131
复制相似问题