gpt4 book ai didi

typescript - TypeScript 中的私有(private) "functions"

转载 作者:搜寻专家 更新时间:2023-10-30 20:28:53 31 4
gpt4 key购买 nike

是否可以在 TypeScript 类中创建私有(private)“函数”(方法)?假设我们有以下 Person.ts TypeScript 文件:

class Person {
constructor(public firstName: string, public lastName: string) {
}

public shout(phrase: string) {
alert(phrase);
}

private whisper(phrase: string) {
console.log(phrase);
}
}

编译后将转换为以下内容:

var Person = (function () {
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.shout = function (phrase) {
alert(phrase);
};
Person.prototype.whisper = function (phrase) {
console.log(phrase);
};
return Person;
})();

观察

我期待 whisper 函数在闭包中声明,而不是在原型(prototype)上声明?本质上,这使得 whisper 函数在编译时公开?

最佳答案

更新。现在实现了使用 # 的私有(private)方法。看这里:https://github.com/microsoft/TypeScript/pull/42458

--

TypeScript 公共(public)/私有(private)关键字仅适用于 TypeScript 检查代码的方式 - 它们对 JavaScript 输出没有任何影响。

根据 the language specification (第 9-10 页):

Private visibility is a design-time construct; it is enforced duringstatic type checking but does not imply any runtime enforcement....TypeScript enforces encapsulation of implementation in classes atdesign time (by restricting use of private members), but cannotenforce encapsulation at runtime because all object properties areaccessible at runtime. Future versions of JavaScript may provideprivate names which would enable runtime enforcement of privatemembers

这已经在这里被询问和回答:https://stackoverflow.com/a/12713869/1014822

更新:这个旧答案仍然有一定的流量,因此值得注意的是,除了上面的语言规范链接外,还详细介绍了公共(public)、私有(private)和(现在) protected 成员在 TypeScript 中 handbook关于类的章节。

2018 年更新ES 私有(private)字段的实现现在是 TypeScript 的 future 项目 RoadMap尽管discussion这表明这将是一个并行的硬私有(private)选项,而不是当前软私有(private)实现的替代品。

2020 年更新使用 # 运算符的运行时私有(private)字段 已从 TS 3.8 开始实现。在 StackOverflow here 上对它们如何工作以及它们与使用 private 关键字的编译时字段有何不同进行了很好的讨论。 .

私有(private)方法已进入 TC39 工作组的第 3 阶段。该功能目前正在针对 TypeScript 进行积极讨论,例如 here .

关于typescript - TypeScript 中的私有(private) "functions",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16919473/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com