【问题标题】:JavaScript ES6 Decorator PatternJavaScript ES6 装饰器模式
【发布时间】:2018-09-19 04:57:48
【问题描述】:

我正在尝试使用 ES6 类语法在 JavaScript 中实现装饰器模式。这是我的方法:

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";
  }
}

当我打电话时

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

我得到的结果是 NaN,但我希望是“18”。我的错在哪里?

【问题讨论】:

  • 好吧,你的 SideDish 方法(你从 Pommes 使用 super 调用)不要 return 任何东西。
  • getPrice(){ super.getPrice(); } 毫无意义。如果除了超级实现之外什么都不做,只需省略方法,直接继承即可。它还在调用Dish.prototype.getPrice,它总是只返回undefined - 没有帮助。
  • 我很确定SideDish 存在问题。如果我尝试var side_dish = new SideDish(new Steak()); side_dish.getPrice(); 我得到undefined(这是在添加提到的缺失返回之后)。所以这可以解释NaN,因为undefined + 5会导致NaN,但我不知道为什么SideDish::getPrice返回未定义而不是超级(可能是因为它是从Dish而不是@调用它987654338@?)

标签: javascript decorator es6-class


【解决方案1】:

所以看起来问题出在您的父装饰器SideDish 上。目前看起来像:

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

Dish 有:

getPrice(){}

这意味着对于Pommes 上的方法:

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

super.getPrice() 正在返回 undefined(从其直接父级 SideDish,转发到 Dish),而不是您所期望的 Steak.getPrice()

当我更新 SideDish 以使用附加(装饰)对象时:

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

然后运行

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

正如预期的那样,我得到了 18 岁。

【讨论】:

  • @Mike,我对你的回答投了赞成票,以弥补 Ele 的酸涩态度。你能帮我回答一下吗?
  • @kshetline 真的很愿意,但不幸的是,这不算数,因为我的声誉低于 15 岁。所以基本上这是 stackoverflow 告诉我是否支持你的答案。对不起。
  • 我为大家投票!你得到一个赞成票!你会得到一个赞成票!
【解决方案2】:

您忘记了SideDish.getPrice() 中的return

return super.getPrice();

您还忘记了SideDish.getDes() 中的return

【讨论】:

  • 天哪,对不起,冒犯了殿下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
  • 2016-02-21
  • 1970-01-01
相关资源
最近更新 更多