Javascript - 原型上的装饰模式不起作用

时间:2017-07-23 17:45:58

标签: javascript decorator

我正在尝试学习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;
    }
  }
}

我将感激你的每一个帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

MacAirComputerDecorator没有原型相关联。您只是在ComputerDecorator构造函数中调用MacAir构造函数。要在cost()中使用MacAir方法,您需要将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)