Javascript js从类中调用静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43614131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:02:20  来源:igfitidea点击:

js call static method from class

javascriptclassstaticthis

提问by Chris

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()

so I don't have to write the class name 'User'.

所以我不必写类名“用户”。

回答by Ninjaneer

From MDN documentation

来自 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.

静态方法调用直接在类上进行,不能在类的实例上调用。静态方法通常用于创建实用程序函数。

For more please see=> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

有关更多信息,请参阅=> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

You can do something like this => this.constructor.staticMethod());to call static method.

你可以做这样的事情 =>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.';
  }
}

回答by Santhosh Kumar

instead of this User.staticMethod() you can add this.constructor.staticMethod()

而不是这个 User.staticMethod() 你可以添加 this.constructor.staticMethod()

回答by Suresh Atta

staticthings bind to class rather than instance. So you must at least specify the class name.

static事物绑定到类而不是实例。所以你至少必须指定类名。

If you don't want to bind to them to a class make them global.

如果您不想将它们绑定到一个类,请将它们设为全局。

回答by Chris C.

In @Ninjaneer 's accepted answer:

在@Ninjaneer 接受的答案中:

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.';   } }

this.constructor.staticMethod()will throw an error because you must call the super constructor before accessing thisin the constructor.

this.constructor.staticMethod()将抛出错误,因为您必须在访问构造函数之前调用超级构造this函数。

Assuming you fix this aforementioned issue, no pun intended, I think the only benefit of calling this.constructor.staticMethod()is that you're not dependent on the name of the class -- if it ever changes. However, this benefit is probably insignificant since it only benefits static method calls made from inside the class. Static method calls made externally would have to be something like StaticMethodCall.constructor.staticMethod()which is defeats the purpose and looks silly.

假设你解决了前面提到的这个问题,没有双关语,我认为调用的唯一好处this.constructor.staticMethod()是你不依赖于类的名称——如果它发生了变化。但是,这种好处可能微不足道,因为它只会从类内部进行的静态方法调用中受益。外部进行的静态方法调用必须是这样的StaticMethodCall.constructor.staticMethod(),这违背了目的并且看起来很傻。

In Summary:

总之:

If you plan on using the static method outside of the class, I'd definitely stick with using StaticMethodCall.staticMethod() since it's more idiomatic and concise.

如果您打算在类之外使用静态方法,我肯定会坚持使用 StaticMethodCall.staticMethod(),因为它更惯用和简洁。

If you only plan on using the static method within the class, then maybe it's ok to to use this.constructor.staticMethod(), but it'll probably confuse other developers and lead them back to this page :-)

如果您只打算在类中使用静态方法,那么使用this.constructor.staticMethod()它可能没问题,但它可能会混淆其他开发人员并将他们带回此页面:-)

回答by Lord

static members of a class in javascript are added as class properties, you can see the list by using code

javascript中类的静态成员被添加为类属性,您可以使用代码查看列表

        console.log(Object.getOwnPropertyNames(PaymentStrategy));

and for accessing the member just

和访问成员只是

const memberFun = PaymentStrategy["memberName"];
//if member is a function then execute 
memberFun();
 //or 
memberFun(data);

example:

例子:

class PaymentStrategy{

    static Card(user){
        console.log(`${user} will pay with a credit card`);
    }

    static PayPal(user){
        console.log(`${user} will pay through paypal`);

    }

    static BKash(user){
        console.log(`${user} will pay through Bkash`);
    }
}

export default PaymentStrategy;

import PaymentStrategy from "./PaymentStrategy";
class Payment{
    constructor(strategy = "BKash"){
        this.strategy = PaymentStrategy[strategy];
        console.log(Object.getOwnPropertyNames(PaymentStrategy));
    }

    changeStrategy(newStratgey){
        this.strategy = PaymentStrategy[newStratgey];

        console.log(`***Payment Strategy Changed***`);
    }

    showPaymentMethod(user){
        this.strategy(user);
    }
}

export default Payment;
```
```
import Payment from "./Payment"


const strategyPattern = (()=>{
    const execute = ()=>{
        const paymentMethod = new Payment();

        paymentMethod.showPaymentMethod("Suru");
        paymentMethod.showPaymentMethod("Nora");

        paymentMethod.changeStrategy("PayPal");

        paymentMethod.showPaymentMethod("Rafiq");
    }
    return{
        execute:execute
    }
})();

export {strategyPattern}
```