user3137766
user3137766

Reputation:

Undefined method in nodejs class exported

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

Upvotes: 0

Views: 64

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

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

Upvotes: 1

Related Questions