angular - Typescript 中的私有(private)参数

标签 angular typescript

我正在学习 Angular2 并第一次在 javascript 中使用 classes

private 参数是什么,为什么它不能简单地是 heroService: HeroService

constructor(private heroService: HeroService) { }

最佳答案

看起来像 parameter property .基本上,向构造函数参数添加访问修饰符(公共(public)/私有(private)/ protected /只读)会自动将该参数分配给同名字段。

具体来说,来自那些文档:

TypeScript offers special syntax for turning a constructor parameter into a class property with the same name and value. These are called parameter properties and are created by prefixing a constructor argument with one of the visibility modifiers public, private, protected, or readonly. The resulting field gets those modifier(s)

所以下面是等价的:

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

class Foo {
    constructor(private bar: string) {}
}

关于angular - Typescript 中的私有(private)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48571592/

相关文章:

angular - 尝试将参数传递给子组件时得到 'Error: Input is not defined'

angular - 我可以共享一个用于 Web 和 Ionic 的 Angular 项目吗?

javascript - Typescript 的错误函数

reactjs - 只允许特定元素作为由 Typescript 检查的 prop

typescript - 在 TypeScript 中创建 "fake"新类型

javascript - 将 Angular2 应用程序的必要依赖项上传到 Web 主机

javascript - rxjs/订阅没有导出成员 'Subscription'

angular - 如何在ag-grid中为angular 2做分页

reactjs - React 将 JSX 应用程序转换为 Typescript

angular - ionic CLI 启动 : starterkit v3?