示例工程 07-classes-interfaces

07-classes-interfaces/04-private-fields/src/main.ts

typescript · 0.8 KB

运行:07 · private-fields

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

// 演示:private 只是编译期检查,#private 是真正的运行时私有
export class LegacySecret {
  private value: string;
 
  constructor(value: string) {
    this.value = value;
  }
 
  reveal(): string {
    return this.value;
  }
}
 
export class HashSecret {
  #value: string;
 
  constructor(value: string) {
    this.#value = value;
  }
 
  reveal(): string {
    return this.#value;
  }
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const legacy = new LegacySecret('legacy');
  const hash = new HashSecret('hash');
  const lines = [
    legacy.reveal(),
    hash.reveal(),
    Object.keys(legacy).join(','),
    Object.keys(hash).join(',') || '(no own keys)',
  ];
  for (const line of lines) {
    log(line);
  }
  return lines;
}