Help me understand how this code call another class property

In this code I dont understand this line
observer => observer.notify()

How it access another property in another class like that ?

class shopper_observer {
    constructor(name) {
        this.name = name;
    }

    notify(categoryName, discount) {
        console.log(`${this.name}, there is a sale for ${categoryName} course. ${discount}% off`);
    }
}

class Category_observable{
    constructor(name) {
        this.name = name;
        this.subscribers = [];
    }

    subscribe(observer) {
        this.subscribers.push(observer);
    }

    sale(discount) {
        this.subscribers.forEach(observer => observer.notify(this.name, discount));
    }
}

const designCategory = new Category_observable("Design Category");
const webCategory = new Category_observable("Web Dev Category");
const pdCategory = new Category_observable("Personal Dev Category");

const paul = new shopper_observer('Paul');
const mike = new shopper_observer('Mike');
const john = new shopper_observer('John');
const alex = new shopper_observer('Alex');

designCategory.subscribe(paul);
designCategory.subscribe(mike);
designCategory.subscribe(john);

webCategory.subscribe(mike);
pdCategory.subscribe(alex);

designCategory.sale(20);
webCategory.sale(15);
pdCategory.sale(25);

That arrow notation is shorthand to define a function, that is similar to:

this.subscribers.forEach(function (observer) {
    observer.notify(this.name, discount);
});
1 Like

Thanks and how it call notify() in another class shopper_observer without using new ?

Well, what is the observer? That is each item in the this.subscribers object, which if you look further down the code, I would argue is updated by the following code:
designCategory.subscribe(paul);

Which consists of the following things:
const paul = new shopper_observer('Paul');

1 Like

So subscribe is adding observers into array and each element of this array is the observer object so I can call any property of that object. Thanks alot

1 Like

Yes, as is seen here:

    subscribe(observer) {
        this.subscribers.push(observer);
    }
1 Like

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