javascript - 在构造函数的参数上使用 this 关键字

标签 javascript typescript constructor tslint tsconfig

name: string;

constructor(private value: string) {
  this.name = value;
  // or 
  this.name = this.value;
}

这些选项中哪个更好。为什么我可以选择在 value 上使用 this 前缀?在构造函数的参数上使用 this 关键字是否有效?

我在 tsconfig 和 tslint 中使用了 noUnusedParametersnoUnusedLocals 来确保我的程序中没有未使用的变量。不幸的是,如果构造函数的参数前面没有 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/

相关文章:

javascript - `this` 在全局上下文和内部函数中

typescript - 为什么 A | B允许两者结合,我该如何防止呢?

javascript - Angular/ typescript : How to resolve this compilation issue?

javascript - TypeScript - 访问内部对象中的变量

c++ - 如何将参数列表存储到 vector ?

php - PHP 中的便捷构造函数

javascript - 在reactjs中使用参数设置背景

javascript - 使用 shift() 和 push() 循环数组值与使用计数器变量相比,最佳方法是什么?

javascript - 在哪里可以找到或覆盖 _navbar.scss?

c++ - 我应该为 std::string 使用右值编写构造函数吗?