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

为何age()的setter中if语句未执行?setter失效但getter正常

问题分析与修复方案

嘿,我来帮你拆解下代码里的几个关键问题,这就是为啥你的setter没生效的原因:

1. Setter 根本没被触发

你现在实例化Player的时候是直接把"38"传给了构造函数的age参数,然后构造函数直接赋值给this._age——这个过程完全没用到set age()!Setter只有在你主动给player.age赋值的时候才会触发,比如test.age = 40,而不是在实例化阶段。

2. Setter 的写法有两个错误

  • 首先,value.isNaN()是错的!isNaN不是字符串/任意值的方法,你得用全局的isNaN(value)或者更严谨的Number.isNaN(value)。如果value是字符串"38",调用value.isNaN()会直接报错,因为字符串原型上没有这个方法。
  • 其次,Setter 不应该返回字符串提示!Setter的返回值会被JavaScript忽略,如果你要校验不通过的情况,应该抛出错误,而不是返回信息。

3. 构造函数没做校验

实例化的时候直接把参数赋值给_age,跳过了校验逻辑,导致一开始_age就被设置成了字符串,这也是getter返回错误提示的原因。


修复后的代码

class Player {
  constructor(name, age, position) {
    this._name = name;
    // 构造函数里调用setter来初始化age,确保校验生效
    this.age = age;
    this._position = position;
  }

  set age(value) {
    // 判断是否为合法数字:要么是数字类型,要么是可转换为数字的字符串
    if (typeof value !== "number" && isNaN(Number(value))) {
      throw new Error("Age must be a number");
    }
    // 统一转换为数字类型后赋值
    this._age = Number(value);
  }

  get name() {
    return this._name;
  }

  get age() {
    return this._age;
  }

  get position() {
    return this._position;
  }
};

怎么测试?

  1. 合法赋值的情况:
const test1 = new Player("Peter", 38, "Forward");
console.log(test1.age); // 输出38

test1.age = "40"; // 字符串形式的数字会被自动转换
console.log(test1.age); // 输出40
  1. 非法赋值的情况:
try {
  const test2 = new Player("John", "abc", "Midfielder");
} catch (err) {
  console.log(err.message); // 输出"Age must be a number"
}

try {
  test1.age = "not a number";
} catch (err) {
  console.log(err.message); // 输出"Age must be a number"
}

内容的提问来源于stack exchange,提问作者Peter Svärd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 00:32:28