name: string;
constructor(private value: string) {
this.name = value;
// or
this.name = this.value;
}
这些选项中哪个更好。为什么我可以选择在 value
上使用 this
前缀?在构造函数的参数上使用 this
关键字是否有效?
我在 tsconfig 和 tslint 中使用了 noUnusedParameters
、noUnusedLocals
来确保我的程序中没有未使用的变量。不幸的是,如果构造函数的参数前面没有 this
,tslint 就会报告它们(将它们标记为未使用,这很奇怪)。
最佳答案
您可以使用 this.value
,因为当您在构造函数中使用访问修饰符将其声明为 private value: string
时,就会对其进行赋值。
如果您不打算在其他函数中使用value
,最好只注入(inject)它,而不提供它和访问修饰符。
name: string;
constructor(value: string) {
this.name = value;
}
关于javascript - 在构造函数的参数上使用 this 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47264737/