Typescript中的私有参数

And*_*rut 8 typescript angular

我正在学习Angular2,并与工作classesjavascript尚属首次.

private参数是什么以及它为什么不能简单heroService: HeroService

constructor(private heroService: HeroService) { }
Run Code Online (Sandbox Code Playgroud)

CRi*_*ice 12

看起来像一个参数属性(大约在页面的一半).基本上,向构造函数参数添加访问修饰符(public/private/protected/readonly)会自动将该参数分配给同名字段.

具体来说,从那些文档:

通过在构造函数参数前添加可访问性修饰符或只读或两者来声明参数属性.使用private作为参数属性声明并初始化私有成员; 同样,公共,受保护和只读也是如此.

所以以下是等价的:

class Foo {
    private bar: string;
    constructor(bar: string) {
        this.bar = bar;
    }
}

class Foo {
    constructor(private bar: string) {}
}
Run Code Online (Sandbox Code Playgroud)