示例工程 14-runtime-syntax

14-runtime-syntax/05-using/src/main.ts

typescript · 0.8 KB

运行:14 · using

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// 演示:using 在作用域结束时自动调用 Symbol.dispose,逆序释放
export class Resource {
  #name: string;
  #log: (msg: string) => void;
 
  constructor(name: string, log: (msg: string) => void) {
    this.#name = name;
    this.#log = log;
    this.#log(`open:${this.#name}`);
  }
 
  use(): void {
    this.#log(`use:${this.#name}`);
  }
 
  [Symbol.dispose](): void {
    this.#log(`dispose:${this.#name}`);
  }
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const lines: string[] = [];
  {
    using first = new Resource('first', (msg) => lines.push(msg));
    using second = new Resource('second', (msg) => lines.push(msg));
    first.use();
    second.use();
  }
  lines.push('after');
  for (const line of lines) {
    log(line);
  }
  return lines;
}