TypeScript私有成员

TypeScript私有成员

本文介绍了TypeScript私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究TypeScript中私有成员的实现,我发现它有点令人困惑。 Intellisense不允许访问私有成员,但在纯JavaScript中,它就在那里。这让我觉得TS没有正确实现私有成员。
有什么想法吗?

I'm looking at implementation of private members in TypeScript, and I find it a little confusing. Intellisense doesn't allow to access private member, but in pure JavaScript, it's all there. This makes me think that TS doesn't implement private members correctly.Any thoughts?

class Test{
  private member: any = "private member";
}
alert(new Test().member);


推荐答案

就像类型检查一样,会员的隐私仅在编译器中强制执行。

Just as with the type checking, the privacy of members are only enforced within the compiler.

私有属性是作为常规属性实现的,并且不允许类外的代码访问它。

A private property is implemented as a regular property, and code outside the class is not allowed to access it.

要在类中创建真正私有的东西,它不能是类的成员,它将是在创建对象的代码内的函数范围内创建的局部变量。这意味着你不能像类的成员那样访问它,即使用这个关键字。

To make something truly private inside the class, it can't be a member of the class, it would be a local variable created inside a function scope inside the code that creates the object. That would mean that you can't access it like a member of the class, i.e. using the this keyword.

这篇关于TypeScript私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:08