我正在尝试使用 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
上。目前看起来像:
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,正如预期的那样。
关于JavaScript ES6 装饰器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49738953/