Help me understand how this code work please

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

    static Paypal(user) {
        console.log(`${user} will pay with paypal`);
    }

    static COD(user) {
        console.log(`${user} will pay with COD`);
    }
}

class Payment {
    
    constructor(strategy = 'Card') {
        this.strategy = PaymentStrategy[strategy];
    }

    changeStrategy(newStrategy) {
        this.strategy = PaymentStrategy[newStrategy];
        console.log('**** Payment method changed ******');
    }

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

const pm = new Payment();
pm.showPaymentMethod('Mike');
pm.showPaymentMethod('Paul');

pm.changeStrategy('Paypal');

pm.showPaymentMethod('Alex');
pm.showPaymentMethod('Mars');

Because I am coming for traditional languages like Pascal it is confusing for me how this.strategy point to a methods Card Paypal and COD ?

Is it normal to access class methods like this: ```
PaymentStrategy[strategy] or it should be PaymentStrategy(strategy) ?

I converted the class code to more normal-looking JavaScript code, but figured that’s too much of a distraction from what’s being asked about.

That’s an example of the strategy pattern.

image

The this.strategy property can, like any other object property, point to anything at all.
In this case, it’s pointing to a payment method that is going to be used.

The former is a property accessor that’s used to access object properties, as well as array items.
The latter is used when you intend for the function to return something.

When the property name is known, it’s preferred to use dot notation which helps to reduce confusion.
PaymentStrategy.Card

When the property name is unknown ahead of time, as is the case here, array notation is used instead.
PaymentStrategy[strategy]

2 Likes

Thanks Paul Wilkins did not saw array notation to access property before.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.