我想修改"名称"通过添加前缀"与suggar"并为成本增加+1。没有添加属性:" coffee.sugar"方法:" this.toString"
function Coffe(name) {
this.name = name;
this.cost = function () {
return 5;
};
this.toString = function () {
return this.name + this.cost() + 'USD';
}
}
var sugar = function () {
coffe.sugar = "with sugar ";
var cost = coffe.cost();
coffe.cost = function () {
return cost + 1;
}
};
var coffe = new Coffe('Latte');
sugar(coffe);
console.log(coffe.cost());

答案 0 :(得分:1)
只需重新分配name
属性:
function Coffe(name) {
this.name = name;
this.cost = function () {
return 5;
};
this.toString = function () {
return this.name + this.cost() + 'USD';
}
}
var sugar = function (coffe) {
coffe.name = "with sugar " + coffe.name;
var cost = coffe.cost();
coffe.cost = function () {
return cost + 1;
}
};
var coffe = new Coffe('Latte');
sugar(coffe);
console.log(coffe.name);
console.log(coffe.cost());
答案 1 :(得分:1)
你的sugar方法没有参数,但是你正在传递你的coffee
实例。只需改变传递的实例的name属性,如下所示:
function Coffe(name) {
this.name = name;
this.cost = function () {
return 5;
};
this.toString = function () {
return this.name + this.cost() + 'USD';
}
}
var sugar = function (coffe) {
coffe.name += " with sugar";
var cost = coffe.cost();
coffe.cost = function () {
return cost + 1;
}
};
var coffe = new Coffe('Latte');
sugar(coffe);
console.log(coffe.cost());
console.log(coffe.name);