我查看了其他在线示例,但它们不起作用。
所以...
我正在尝试在 JavaScript 中实现“Head First”中的经典“装饰器模式”......而且我真的很接近。
鉴于以下“课程”:
// "CLASSES": BEVERAGES
function DarkRoast(){
this.cost = 1.00;
this.description = "Dark Roast";
};
// DECORATORS: CONDIMENTS
function Milk(beverage){
var instance = beverage;
beverage.cost = function(){
return instance.cost + 0.25;
};
beverage.description = functionn(){
return instance.description + ', Milk';
};
};
问题:如何从以下函数动态实例化“牛奶”?
function appendCondiment(className, beverage) {
/* Needs to do this, but dynamically:
var instance = new Milk(beverage); */
// This fails (of course)
var instance = new window[className].call(beverage);
}