到目前为止,我一直使用下面的代码来定义TypeScript
中的构造函数。
export class DashboardComponent {
private heroService: HeroService;
constructor(heroService: HeroService){
this.heroService = heroService
}
}
但是最近当我检查Angular 2
文档时,我看到语法更短,看起来像
export class DashboardComponent {
constructor(private heroService: HeroService){}
}
和编译后的JavaScript是一样的
var DashboardComponent = (function () {
function DashboardComponent(heroService) {
this.heroService = heroService;
}
return DashboardComponent;
}());
因为在TypeScript
文档上只显示第一种类型,所以我只是想确保两种类型是相同的,并且我对这两种类型都做得正确。
是的,这两种写法实际上是一样的。您可以在GitHub上的官方语言规范中看到第二个与public
一起使用。
class BankAccount {
constructor(public balance: number) {}
}
与
相同class BankAccount {
public balance: number
constructor(balance: number) {
this.balance = balance;
}
}
另外,关于生成的JavaScript代码的注意事项:使用private
或public
不会改变输出。因为在纯JavaScript中,没有"私有"成员这样的东西:您无法阻止对对象成员的访问。public
和private
唯一的作用是告诉TypeScript其他代码应该访问什么,不应该访问什么。