【问题标题】:Javascript - Decorator pattern on prototype dont workJavascript - 原型上的装饰器模式不起作用
【发布时间】:2017-07-23 17:45:58
【问题描述】:

我正在尝试学习 js 中的装饰器模式。你能解释一下,为什么ComputerDecorator 没有cost() 方法?这是我的代码:

function Computer(){
  this._cost = 3000;
}

Computer.prototype.cost = function(){
  return this._cost;
}

function ComputerDecorator(computer){
    Computer.call(this);
    this.computer = computer;
}

ComputerDecorator.prototype = Object.create(Computer.prototype);
ComputerDecorator.prototype.cost = function(){
  return this._cost  + this.computer.cost();
};

function MacAir(computer){
  ComputerDecorator.call(this, computer);
  this._cost = 2500;
}

var mac = new Computer();
mac = new MacAir(mac);
console.log(mac)

这里是控制台日志:

[object Object] {
  _cost: 2500,
  computer: [object Object] {
    _cost: 3000,
    cost: function (){
    return this._cost;
    }
  }
}

我会感激每一个帮助。谢谢!

【问题讨论】:

  • 您正在创建一个公共的_cost 实例属性(因为您使用了this._cost)和一个公共继承的cost 方法。要真正封装数据,this._cost 应该是var _cost。否则,有人可能会绕过您的方法并简单地获取 _cost 属性值。

标签: javascript decorator


【解决方案1】:

MacAir 没有与ComputerDecorator 原型链接。您只是在MacAirconstructor 中调用ComputerDecorator 构造函数。为了在MacAir 中拥有cost() 方法,您需要将MacAirComputerDecorator 原型链接,如下所示:

function Computer(){
  this._cost = 3000;
}

Computer.prototype.cost = function(){
  return this._cost;
}

function ComputerDecorator(computer){
    Computer.call(this);
    this.computer = computer;
}

ComputerDecorator.prototype = Object.create(Computer.prototype);
ComputerDecorator.prototype.cost = function(){
  return this._cost  + this.computer.cost();
};

function MacAir(computer){
  ComputerDecorator.call(this, computer);
  this._cost = 2500;
}
MacAir.prototype = Object.create(ComputerDecorator.prototype);

var mac = new Computer();
mac = new MacAir(mac);
console.log(mac)

【讨论】:

  • 没错。我忘记了将 MacAir 与 ComputerDecorator 联系起来。非常感谢。 (;
猜你喜欢
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 2018-09-19
  • 2015-08-06
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多