如何操作类属性?我想在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 }
关键说明
属性赋值逻辑:
使用this[property] = newValue来动态修改属性,这是JS中通过变量/字符串访问对象属性的标准方式(区别于.语法只能用固定属性名)。属性校验(可选):
加入hasOwnProperty校验是为了防止误修改或添加Item类原本不存在的属性,提升代码健壮性。如果不需要校验,直接写this[property] = newValue也能实现基本功能。调用方式修正:
原代码中dentist.edit(title, "Appointment")里的title是未定义的变量,会导致报错,必须改成字符串"title"才能正确指定要修改的属性名。
内容的提问来源于stack exchange,提问作者Monnt
相关产品推荐
相关产品推荐

