js call static method from class

后端 未结 5 2146
南旧
南旧 2020-12-03 16:49

I have a class with a static method:

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

  static staticMethod() {}
}

Is there som

5条回答
  •  -上瘾入骨i
    2020-12-03 17:16

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

            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}
    ```
    
    

提交回复
热议问题