如何显示函数装饰器的消息?

时间:2018-05-11 14:26:57

标签: javascript

当我调用方法to.String

时,我想显示一条咖啡大小的消息



{{1}}




1 个答案:

答案 0 :(得分:1)

稍作修改即可。

function Coffe(name) {
    // I would recommend setting some appropriate default value to
    // this.size since every coffee has a size (you might omit this.size 
    // declaration here but then you will not get a pretty toString output
    // without calling small)
    this.size = "";
    this.name = name;
    this.cost = function () {
        return 5;
    };
    this.toString = function () {
        return this.name + this.cost() + ' USD '+ this.size;
    }
}

// pass a coffee instead of size - which was coffee anyway
const small = function(coffe) {
    coffe.size = "small";     // change size of the provided coffee
    let cost = coffe.cost();
    coffe.cost = function () {
        return cost - 1;
    }
};

var coffe = new Coffe('Latte ');
small(coffe);
console.log(String(coffe));