You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改构造函数实例的属性?为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 sugar function doesn't accept the coffee instance as a parameter, so it's relying on a global coffe variable—this makes the function inflexible and prone to bugs.
  • Right now, it only adds a sugar property to the instance, but doesn't modify the name property directly, which is what you actually need.
  • There's a small risk of recursive calls if we don't handle the cost function 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 name directly: By directly prepending "with sugar " to the existing name property, we don't need to touch the toString method at all—it will automatically use the updated name, which meets your requirement perfectly.
  • Safe cost adjustment: We first capture the original cost value returned by the instance's cost function. Then we redefine cost to return that original value plus 1. This prevents issues like recursive calls (if we tried to call coffee.cost() inside the new function) or repeated increments if we ever call sugar multiple times on the same instance.
  • Parameterized function: Passing the coffee instance as a parameter makes the sugar function reusable with any Coffe instance, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:08:46