如何修改构造函数实例的属性?为Coffe实例添加前缀并调整成本
Hey there! Let's work through fixing your Coffe (I'll stick with your spelling here) instance modification problem. Your requirements are clear: add the "with sugar " prefix to the name property, bump the cost return value by 1, and avoid relying on a separate sugar property in the toString method. Let's break this down step by step.
First, let's spot the issues in your original code
- The
sugarfunction doesn't accept the coffee instance as a parameter, so it's relying on a globalcoffevariable—this makes the function inflexible and prone to bugs. - Right now, it only adds a
sugarproperty to the instance, but doesn't modify thenameproperty directly, which is what you actually need. - There's a small risk of recursive calls if we don't handle the
costfunction properly (but we'll fix that too).
Here's the corrected code
function Coffe(name) { this.name = name; this.cost = function () { return 5; }; this.toString = function () { return this.name + ' ' + this.cost() + 'USD'; // Added a space for cleaner formatting }; } // Updated sugar function that takes the coffee instance as a parameter var sugar = function (coffee) { // Directly prepend the prefix to the name property—no extra sugar property needed coffee.name = "with sugar " + coffee.name; // Capture the original cost value first to avoid recursive calls or repeated increments const originalCost = coffee.cost(); coffee.cost = function () { return originalCost + 1; }; }; var coffe = new Coffe('Latte'); sugar(coffe); console.log(coffe.cost()); // Outputs: 6 console.log(coffe.toString()); // Outputs: "with sugar Latte 6USD"
Key changes explained
- Modifying the
namedirectly: By directly prepending "with sugar " to the existingnameproperty, we don't need to touch thetoStringmethod at all—it will automatically use the updated name, which meets your requirement perfectly. - Safe
costadjustment: We first capture the original cost value returned by the instance'scostfunction. Then we redefinecostto return that original value plus 1. This prevents issues like recursive calls (if we tried to callcoffee.cost()inside the new function) or repeated increments if we ever callsugarmultiple times on the same instance. - Parameterized function: Passing the coffee instance as a parameter makes the
sugarfunction reusable with anyCoffeinstance, instead of being tied to a single global variable.
This solution hits all your requirements and keeps the code clean and maintainable.
内容的提问来源于stack exchange,提问作者Igor Shvets
相关产品推荐
相关产品推荐

