0

i'm little bit confused with my code below, i am trying to access the subscribers attribute of a Category class and get undefined:

class Category {
    constuctor(name){
        this.name = name; // Category name
        this.subscribers = [];
    }
    subcribe(observer){
        console.log(this.subcribers)
        this.subscribers.push(observer)// <----------- this is undefined ????
    }

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

module.exports = Category;

// Observer 
class Shopper {
    notify(name, discount){ console.log(name, discount) }
}
module.exports = Shopper;

Form main file

const Category = require('./Category')
const Shopper = require('./Shopper')
const book = new Category("Book");
const shopper = new Shopper("PAUL")
const subscribe = book.subscribe(shopper);

// Output : TypeError: Cannot read property 'push' of undefined

Why this.subscribers is undefined ? thanks for your help

Thanks guys

1 Answer 1

1

The code is riddled with typos: constructor not constuctor, subscribe not subcribe, subscribers not subcribers, discount not disoucnt.

Because of the constructor typo your class was not even getting instantiated.

class Category {
  constructor(name){
      this.name = name; // Category name
      this.subscribers = [];
  }
  subscribe(observer){
      console.log(this.subscribers)
      this.subscribers.push(observer)
      console.log(this.subscribers)
  }

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

// module.exports = Category;

// Observer 
class Shopper {
  notify(name, discount){ console.log(name, discount) }
}
// module.exports = Shopper;

const book = new Category("Book");
const shopper = new Shopper("PAUL")
const subscribe = book.subscribe(shopper);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.