gpt4 book ai didi

javascript - JS从类中调用静态方法

转载 作者:行者123 更新时间:2023-12-03 02:20:48 25 4
gpt4 key购买 nike

我有一个带有静态方法的类:

class User {
constructor() {
User.staticMethod();
}

static staticMethod() {}
}

静态方法是否有与此等效的方法(即引用没有实例的当前类)?

this.staticMethod()

所以我不必写类名:“User”。

最佳答案

来自 MDN 文档

Static method calls are made directly on the class and are notcallable on instances of the class. Static methods are often used tocreate 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com