我想在调用to.String方法时显示一条咖啡大小的消息
function Coffe(name) {
this.name = name;
this.cost = function () {
return 5;
};
this.toString = function () {
return this.name + this.cost() + ' USD '+ this.size;
}
}
var small = function (size) {
this.size = size;
size = "small";
var cost = coffe.cost();
coffe.cost = function () {
return cost - 1;
}
};
var coffe = new Coffe('Latte ');
small(coffe);
console.log(String(coffe));
最佳答案
一点点修改,就可以了。
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));