为什么在类的构造函数中声明的属性不存在? [英] Why is property declared in a constructor of a class not exist?

查看:89
本文介绍了为什么在类的构造函数中声明的属性不存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

constructor (service: MyService) {}

ngOnInit() {
    this.service.init();
}

在上面的代码中,我得到:-

In the above code, I'm getting:-

Property `service` does not exist on type 'MyComponment'

但是,如果我将 service 声明为 private ,则它可以正常工作.这是怎么回事?

Yet, if I declare service as private it works. What is going on here?

-

[Angular 8.2.12,TypeScript 3.5.3]

[Angular 8.2.12, TypeScript 3.5.3]

推荐答案

来自

通过在构造函数参数前面声明参数属性使用可访问性修饰符或 readonly 或同时使用两者.使用 private 对于参数属性,声明并初始化一个私有成员;同样,对于 public protected readonly 也是如此.

Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or readonly, or both. Using private for a parameter property declares and initializes a private member; likewise, the same is done for public, protected, and readonly.

没有前缀,构造函数参数只不过是方法参数,您必须从构造函数本身将其手动分配给已声明的类属性.

Without the prefix, the constructor parameter is nothing more than a method parameter, and you would have to manually assign it to a declared class property from the constructor itself.

相关的SO帖子

这篇关于为什么在类的构造函数中声明的属性不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆