1

我查看了其他在线示例,但它们不起作用。

所以...

我正在尝试在 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);
}
4

2 回答 2

0

怎么样:

var DarkRoast = function () {
    this.cost = 1.00;
    this.description = 'Dark Roast';
};

var condiments = {
    milk: {
        cost: 0.25;
        description: 'Milk'
    },
    cream: {
        cost: 0.3,
        description: 'Cream'
    }
};

var appendCondiment = function ( condimentName, beverage ) {
    var condiment = condiments[ condimentName ];
    beverage.cost += condiment.cost;
    beverage.description += ', ' + condiment.description;
};

用法:

var bev = new DarkRoast();
appendCondiment( 'milk', bev );

bev.cost // 1.25
bev.description // 'Dark Roast, Milk'

顺便说一句,考虑DarkRoast从一个类继承Beverage,然后定义一个appendCondiment方法来Beverage.prototype. 然后你就可以这样写:

var bev = new DarkRoast();
bev.appendCondiment( 'milk' );

哪个更具可读性。

于 2012-08-19T12:06:49.927 回答
0

你需要:

var instance = new window[className](beverage);
于 2012-08-19T11:54:47.433 回答