Setter 和 Getter 问题

Setter and Getter problems

为什么 age() 的 setter 中的 if 语句没有执行?应该return "年龄必须是数字";

get 语句有效,但 set 语句无效。

class Player {
    constructor(name, age, position) {
        this._name = name;
        this._age = age;
        this._position = position;
    }
set age(value){ 
    if(value.isNaN()) {
        return "Age must be a number";
    } else {
        return this._age;
    }
}
get name() {
        return this._name;
    }
get age() {
    if(typeof this._age === "number") {
        return this._age;
    }else{
        return "Cant fetch players age"
    }
}
get position() {
    return this._position;
}
};
const test = new Player("Peter", "38", "Forward")
console.log(test.age)

你的构造函数应该调用 setter 而不是实例变量:

class Player {
    constructor(name, age, position) {
        this._name = name;
        this.age = age;  //call setter
        this._position = position;
    }
    ...