TypeScript 中私有关键字和私有字段的区别
TypeScript 3.8 支持private 关键字将其成员声明为私有。 TypeScript 中的私有字段是 JavaScript 新提出的。这些字段以#开头。
Private 关键字: TypeScript 中的 private 关键字用于将成员标记为私有,使其在声明的类之外无法访问。这些字段前面有private关键字以将它们标记为私有。
- 句法:
private variableName
- 例子:
class letters { private a; constructor(alphabet){ this.a = alphabet; } getA(){ return this.a; } } const l = new letters("gfg"); console.log(l.getA());
- 输出:
gfg
私有字段: TypeScript 中的私有字段是新添加到 JavaScript 中的字段,要声明为私有的成员以#开头。私有成员不能在他们的类之外被访问。
- 句法:
#variableName
- 例子:
class letters { #a; constructor(alphabet){ this.#a = alphabet; } getA(){ return this.#a; } } const l = new letters("gfg"); console.log(l.getA());
输出:
gfg
因此,在将 TypeScript 编译为 ESNext JavaScript 时,要在运行时实现 private 关键字,必须考虑使用为 JavaScript 定义的私有语法# 。
私有关键字和私有字段的区别:
Private keyword | Private fields |
---|---|
It is a TypeScript modifier. | It is a newly added syntax by ECMA to JavaScript, which is also available in TypeScript. |
It is a compile time annotation. So, when a transpiler converts TypeScript code to JavaScript, the private keyword is removed. | The private fields remain private at runtime even after the TypeScript code gets converted to JavaScript by the transpiler. |