在TypeScript中手动和自动分配构造函数参数



到目前为止,我一直使用下面的代码来定义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代码的注意事项:使用privatepublic不会改变输出。因为在纯JavaScript中,没有"私有"成员这样的东西:您无法阻止对对象成员的访问。publicprivate唯一的作用是告诉TypeScript其他代码应该访问什么,不应该访问什么。

相关内容

最新更新