Mikelgo
Mikelgo

Reputation: 575

JavaScript ES6 Decorator Pattern

I'm trying to implement the decorator pattern in JavaScript with ES6 Class-Syntax. Here is my approach:

class Dish{
  constructor(){}
  getPrice(){}
  getDes(){}
}

class Steak extends Dish{
  constructor(){
    super();
  }
  getPrice(){
    return 13;
  }
  getDes(){
    return "Steak";
  }
}

class SideDish extends Dish{
  constructor(dish){
    super();
    this.dish = dish;
  }
  getPrice(){
    return super.getPrice();
  }
  getDes(){
    return super.getDes();
  }
}

class Pommes extends SideDish{
  constructor(dish){
    super(dish);
  }
  getPrice(){
    return super.getPrice() +5;
  }
  getDes(){
    return super.getDes() + " Pommes";
  }
}

When I'm calling

var dish = new Pommes(new Steak());
dish.getPrice();

The result im getting is NaN but I would expect "18". Where's my fault?

Upvotes: 2

Views: 1688

Answers (2)

Anthony
Anthony

Reputation: 37065

So it looks like the issue is with your parent decorator SideDish. It currently looks like:

class SideDish extends Dish{
   constructor(dish){
     super();
     this.dish = dish;
  }
  getPrice(){
     return super.getPrice();
  }
  getDes(){
     return super.getDes();
  }
}

with Dish having :

getPrice(){}

This means that for the method on Pommes :

  getPrice(){
     return super.getPrice() +5;
  }

super.getPrice() is returning undefined (from its direct parent, SideDish, forwarded to Dish), not to Steak.getPrice() as you are expecting.

When I update SideDish to use the attached (decorated) object like:

class SideDish extends Dish{
  constructor(dish){
     super();
     this.dish = dish;
  }
  getPrice(){
     return this.dish.getPrice();
  }
  getDes(){
     return this.dish.getDes();
  }
}

and then run

var dish = new Pommes(new Steak());
dish.getPrice();

I get 18, as expected.

Upvotes: 3

kshetline
kshetline

Reputation: 13682

You forgot the return in SideDish.getPrice().

return super.getPrice();

You also forgot the return in SideDish.getDes().

Upvotes: 3

Related Questions