gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:31:59 26 4
gpt4 key购买 nike

我正在学习 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com