🎯 学习目标

  • 理解只读属性的概念
  • 掌握 readonly 修饰符的使用
  • 学会在构造函数中初始化只读属性
  • 了解 readonly 与 private 的区别

📝 基本使用

class User { // 只读属性:只能在声明时或构造函数中赋值 readonly id: number; readonly createdAt: Date = new Date(); constructor( id: number, public name: string // 普通属性 ) { this.id = id; } } const user = new User(1, 'Alice'); console.log(user.id); // 1 console.log(user.createdAt); // Date // user.id = 2; // Error: 只读属性不可修改 // user.createdAt = new Date(); // Error user.name = 'Bob'; // OK: 普通属性可修改

🔧 参数属性

class User { constructor( readonly id: number, public name: string, readonly createdAt: Date = new Date() ) {} } const user = new User(1, 'Alice'); console.log(user.id); // 1 console.log(user.name); // Alice console.log(user.createdAt); // Date
💡
参数属性

readonly 可以与访问修饰符一起在构造函数参数中使用,自动创建并初始化属性。

🔒 readonly 与其他修饰符

class Config { // public readonly(默认 public) readonly apiUrl: string; // private readonly private readonly apiKey: string; // protected readonly protected readonly timeout: number; constructor(apiUrl: string, apiKey: string, timeout: number = 5000) { this.apiUrl = apiUrl; this.apiKey = apiKey; this.timeout = timeout; } getApiKey(): string { return this.apiKey; // 内部可访问 } } const config = new Config('https://api.example.com', 'secret'); console.log(config.apiUrl); // OK: public readonly // config.apiUrl = 'new-url'; // Error: readonly // config.apiKey; // Error: private

📝 本节小结

  • • readonly 属性只能赋值一次
  • • 可以在声明或构造函数中初始化
  • • 可与访问修饰符组合使用
  • • 适合不可变的数据