JavaScript ES6 装饰器模式

标签 javascript decorator es6-class

我正在尝试使用 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/

相关文章:

javascript - 如何让ES6类的静态函数中的this指向函数本身

javascript - 如何在可编辑的div中的给定位置设置光标

javascript - jQuery UI Selectables - 从对象外部开始拖动选择

JavaScript 未在 Rails 测试环境中加载

装饰器的 Python 3 类型提示

JavaScript 扩展类,同时使用 Wea​​kMap 作为私有(private)变量

javascript - 在 PhantomJS 上运行时 Karma 测试失败

.net - 我可以告诉 .net 的 Intellisense 如何对字段进行排序吗?

python - 带装饰器的线程

typescript - 使用 TypeScript 装饰器扩展 ES6 类时扩展类型