我正在尝试学习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;
}
}
}
我将感激你的每一个帮助。谢谢!
答案 0 :(得分:0)
MacAir
与ComputerDecorator
没有原型相关联。您只是在ComputerDecorator
构造函数中调用MacAir
构造函数。要在cost()
中使用MacAir
方法,您需要将MacAir
与ComputerDecorator
原型相关联,如下所示:
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)