You need to enable JavaScript to run this app. 如何实现Class实例字段不可重写 仅允许构造函数内一次性赋值
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Class实例字段不可重写 仅允许构造函数内一次性赋值

实现仅构造函数可赋值、后续修改报错的类字段方案

Object.defineProperty完全适用,是实现该需求的核心原生API,以下是两种常见实现方案:

方案1:通过writable: false属性描述符实现

逻辑:构造函数内完成字段赋值后,立刻修改属性描述符将其设为不可写,同时可设置configurable: false禁止后续修改属性规则。

class Room {
  constructor(length, width) {
    // 构造函数内完成首次赋值
    this.length = length;
    this.width = width;
    
    // 锁死两个字段的写权限
    Object.defineProperty(this, 'length', { 
      writable: false,
      configurable: false
    });
    Object.defineProperty(this, 'width', { 
      writable: false,
      configurable: false
    });
  }
}

// 测试效果
let room = new Room(20, 10); 
console.log(room.length) // 输出 20
room.length = 10000 // 严格模式下直接抛出TypeError,非严格模式下赋值静默失败

如果需要适配非严格模式下也抛出错误,可选择第二种方案。

方案2:通过存取器属性(getter/setter)实现

逻辑:将对外暴露的字段设为存取器,setter逻辑直接抛出错误,仅在构造函数内给内部存储的私有变量赋值。

class Room {
  constructor(length, width) {
    // 仅构造函数内给内部私有变量赋值
    this._length = length;
    this._width = width;
  }

  get length() {
    return this._length;
  }
  set length(_) {
    throw new TypeError("Cannot assign to read only property 'length' of object '#<Room>'");
  }

  get width() {
    return this._width;
  }
  set width(_) {
    throw new TypeError("Cannot assign to read only property 'width' of object '#<Room>'");
  }
}

// 测试效果
let room = new Room(20, 10); 
console.log(room.length) // 输出 20
room.length = 10000 // 无论是否开启严格模式,都直接抛出错误

如果需要批量处理多个只读字段,可以封装通用工具函数批量设置属性描述符,减少重复代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 01:54:01