【发布时间】: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