如何在JavaScript中创建对象并正确添加getters和setters(参考Java User类)
实现方案
核心逻辑
- 用JS的
class语法对应Java的类结构,用#前缀定义私有字段,和Java的private修饰符作用一致,禁止外部直接访问属性 - getter通过
get 属性名()声明,setter通过set 属性名(新值)声明,访问时和普通属性读写语法一致 - 原Java代码中的
uuid仅在构造函数初始化,因此仅开放getter,不提供setter避免被修改
完整实现代码
class User { // 私有属性声明,#前缀为JS标准私有字段语法 #uuid; #nickName; #coins; #level; #exp; constructor(uuid) { this.#uuid = uuid; // 初始化默认值和Java代码完全对齐 this.#nickName = null; this.#coins = 0; this.#level = 1; this.#exp = 0; } // uuid仅提供getter,不允许修改 get uuid() { return this.#uuid; } get nickName() { return this.#nickName; } set nickName(newName) { // 可根据业务需求添加自定义校验规则 if ((typeof newName === 'string' && newName.trim()) || newName === null) { this.#nickName = newName; } else { throw new Error('昵称格式不合法'); } } get coins() { return this.#coins; } set coins(newCoins) { if (typeof newCoins === 'number' && !isNaN(newCoins)) { this.#coins = newCoins; } else { throw new Error('coins必须为数字类型'); } } get level() { return this.#level; } set level(newLevel) { if (Number.isInteger(newLevel) && newLevel >= 1) { this.#level = newLevel; } else { throw new Error('等级必须为大于等于1的整数'); } } get exp() { return this.#exp; } set exp(newExp) { if (typeof newExp === 'number' && newExp >= 0) { this.#exp = newExp; } else { throw new Error('经验值不能为负数'); } } }
使用示例
// 生成UUID,和Java的UUID功能对应 const user = new User(crypto.randomUUID()); // 调用setter赋值 user.nickName = "测试用户"; user.coins = 200.75; user.level = 3; user.exp = 120.5; // 调用getter取值 console.log(user.uuid); // 输出用户uuid console.log(user.nickName); // 输出 测试用户 // 直接访问私有属性会抛出语法错误 // console.log(user.#uuid); // 报错:Private field '#uuid' must be declared in an enclosing class
低版本兼容方案
如果运行环境不支持JS私有字段语法,可以用_前缀作为私有属性的语义约定,仅做标识无强制访问限制:
class User { constructor(uuid) { this._uuid = uuid; this._nickName = null; this._coins = 0; this._level = 1; this._exp = 0; } get uuid() { return this._uuid; } // 其余getter、setter逻辑和上述实现完全一致,仅把属性前缀从#改为_即可 }
内容的提问来源于stack exchange,提问作者MENNQ
相关产品推荐
相关产品推荐

