← 中文资源

简体中文版本

多态 this 类型支撑链式调用

链式方法返回 this 而不是类名:子类新增的 limit() 之后仍能接 orderBy(),类型随接收者走,基类实例上则天然没有子类方法。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

select * where status = active limit 10 order by created_at
select * where id = 1

实现说明

多态 this 类型支撑链式调用的核心是类 Query、PagedQuery。 各个操作都建立在顶层绑定之上:base。 结果是全新构造,调用方可以放心保留自己的原件。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 跨调用保留的状态放在这些顶层绑定里:base。

核心语句

return ['select *', ...this.clauses].join(' ');

代码示例

// 多态 this:方法返回 this 而不是具体类名,
// 子类扩展的方法才能继续出现在链式调用的检查里
class Query {
  protected clauses: string[] = [];

  where(condition: string): this {
    this.clauses.push('where ' + condition);
    return this;
  }

  orderBy(field: string): this {
    this.clauses.push('order by ' + field);
    return this;
  }

  build(): string {
    return ['select *', ...this.clauses].join(' ');
  }
}

class PagedQuery extends Query {
  limit(count: number): this {
    this.clauses.push('limit ' + count);
    return this;
  }
}

// limit() 之后仍能调用 orderBy():返回类型随接收者走
const q = new PagedQuery()
  .where('status = active')
  .limit(10)
  .orderBy('created_at');

console.log(q.build());

// 基类实例上没有 limit:链路自然停在基类方法
const base = new Query().where('id = 1');
console.log(base.build());