JavaScript 模拟装饰者模式
作者:互联网
/** * 抽象coffee父类,其实可以不用的 */ function Coffee () {} Coffee.prototype.cost = function() { throw '实现这个方法'; }; /** * 黑咖啡,其实可以不用继承的; */ function BlackCoffee () {} // BlackCoffee.prototype = new Coffee(); // BlackCoffee.prototype.constructor = BlackCoffee; BlackCoffee.prototype.cost = function() { return 1.99; }; /** * 糖,其实可以不用继承的; */ function Milk (coff) { this.coffee = coff; } // Milk.prototype = new Coffee(); // Milk.prototype.constructor = Milk; Milk.prototype.cost = function() { return this.coffee.cost() + 0.2; }; /** * 可以开店卖咖啡了; */ var bc = new BlackCoffee(); var addMilk = new Milk(bc); console.log(addMilk.cost());
标签:function,Coffee,JavaScript,BlackCoffee,Milk,cost,prototype,装饰,模拟 来源: https://blog.51cto.com/u_15241951/2841071