实现说明
除了类 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());