Typescript中的私有参数 [英] Private parameters in Typescript
问题描述
我正在学习Angular2
,并且是第一次在javascript
中与classes
一起工作.
I am learning Angular2
and working with classes
in javascript
first time.
private
参数是什么?为什么不能简单地称为heroService: HeroService
?
What does the private
parameter and why it couldn't be simply heroService: HeroService
?
constructor(private heroService: HeroService) { }
推荐答案
看起来像参数属性(大约在页面的一半).基本上,向构造函数参数添加访问修饰符(公共/私有/受保护/只读)会自动将该参数分配给同名字段.
Looks like a parameter property (about halfway down the page). Basically, adding an access modifier (public/private/protected/readonly) to a constructor parameter will automatically assign that parameter to a field of the same name.
具体来说,从那些文档中:
Specifically, from those docs:
通过在构造函数参数前面声明参数属性 使用可访问性修饰符或只读,或同时使用两者.使用私人 参数属性声明并初始化私有成员; 同样,对public,protected和readonly也是如此.
Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or readonly, or both. Using private for a parameter property declares and initializes a private member; likewise, the same is done for public, protected, and readonly.
所以以下是等效的:
class Foo {
private bar: string;
constructor(bar: string) {
this.bar = bar;
}
}
class Foo {
constructor(private bar: string) {}
}
这篇关于Typescript中的私有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!