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

如何操作类属性?我想在Item类中实现edit方法修改指定属性值

实现Item类的edit属性修改方法

核心问题解决

你当前的代码有两个需要调整的地方:

  • edit 方法未实现属性赋值逻辑
  • 调用 edit 时,属性名参数应该传字符串而非未定义的变量

完整实现代码

class Item {
    constructor(title, description, date, done = false) {
        this.title = title;
        this.description = description;
        this.date = date;
        this.done = done;
    }

    edit(property, newValue) {
        // 可选:校验属性是否存在,避免添加不存在的属性
        if (Object.prototype.hasOwnProperty.call(this, property)) {
            this[property] = newValue;
        } else {
            console.warn(`Item类不存在${property}属性`);
        }
    }
}

const dentist = new Item("Dentist appointment", "With Sally", "19/06/2024")
// 属性名必须传字符串形式
dentist.edit("title", "Appointment")
console.log(dentist) 
// 输出:Item { title: 'Appointment', description: 'With Sally', date: '19/06/2024', done: false }

关键说明

  1. 属性赋值逻辑:
    使用 this[property] = newValue 来动态修改属性,这是JS中通过变量/字符串访问对象属性的标准方式(区别于.语法只能用固定属性名)。

  2. 属性校验(可选):
    加入 hasOwnProperty 校验是为了防止误修改或添加Item类原本不存在的属性,提升代码健壮性。如果不需要校验,直接写 this[property] = newValue 也能实现基本功能。

  3. 调用方式修正:
    原代码中 dentist.edit(title, "Appointment") 里的 title 是未定义的变量,会导致报错,必须改成字符串 "title" 才能正确指定要修改的属性名。

内容的提问来源于stack exchange,提问作者Monnt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:52:08