带访问修饰符的构造函数参数与不带访问修饰符的构造函数参数在整个类中的访问权限

rah*_*ahs 3 angular

角5

为什么只有构造函数签名中使用访问修饰符限定的变量才能在整个类中被识别?

例如。

constructor(private n: number) { 
} 

fn(){
  this.n = 6; //Allowed
}
Run Code Online (Sandbox Code Playgroud)

constructor(n: number) { 
} 

fn(){
  this.n = 6; //Not allowed
}
Run Code Online (Sandbox Code Playgroud)

小智 7

简单的变量范围。

当你写的时候

constructor(x) {}
Run Code Online (Sandbox Code Playgroud)

x只能在构造函数内访问。

使用访问修饰符,您可以将其定义为类成员,从而更改类的范围。


Sh.*_*vel 5

因为,当您使用标有私有(或公共)访问修饰符(来自 Typescript)的输入参数定义构造函数时,它会告诉您的类创建该属性并进行赋值。以下示例执行相同的操作:

constructor(public a, private b) {}
Run Code Online (Sandbox Code Playgroud)
public a;
private b;

constructor(a, b) {
  // a and b are locally scoped to this constructor method, and 
  // are not the same as the property methods this.a and this.b, 
  // so they need to be assigned in order to be accessible in the class
  this.a = a;
  this.b = b;
}
Run Code Online (Sandbox Code Playgroud)

当您在没有访问修饰符(仅对于构造函数而言是本地的)的情况下执行此操作时,您需要自己定义该类属性,如第二个示例中所示。

您可以在该页面上阅读更多相关信息以更好地理解它:

Typescript 中的类

而且,这是同样的问题和有用的答案:

点击