← 中文资源

简体中文版本

参数属性声明构造器字段

用 private、public、protected 修饰构造器参数属性,自动生成实例字段,并在子类与外部读取不同可见性。

阅读英文原文

实现说明

除了类 HttpClient、AdminClient,文件里再无其他定义。 各个操作都建立在顶层绑定之上:client。

使用要点

  • 每一步打印都带着自己的标签:public field:、protected field:。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 文件用顶层绑定保存自己的状态:client。

核心语句

return this.baseUrl + ' timeout=' + this.timeoutMs + ' retries=' + this.retries;

代码示例

// Parameter properties declare instance fields from constructor arguments.
class HttpClient {
  constructor(
    private readonly baseUrl: string,
    public readonly timeoutMs = 5_000,
    protected readonly retries = 2,
  ) {}

  describe(): string {
    return this.baseUrl + ' timeout=' + this.timeoutMs + ' retries=' + this.retries;
  }
}

class AdminClient extends HttpClient {
  showRetries(): number {
    return this.retries;
  }
}

const client = new HttpClient('https://api.example.com', 2_500);
console.log(client.describe());
console.log('public field:', client.timeoutMs);
console.log('protected field:', new AdminClient('https://admin.example.com').showRetries());