typescript 为什么要在 angular4 的打字稿类的字段中添加下划线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45167199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:43:43  来源:igfitidea点击:

Why are underscores added to fields of a typescript class in angular4?

angulartypescriptintellij-idea

提问by Dan

I am building an Angular4project and using IntelliJ. Whenever I create a new class, and then add gettersand setters. The IDE adds underscores to the fields.

我正在构建一个Angular4项目并使用IntelliJ。每当我创建一个新类,然后添加gettersetter。IDE 会向字段添加下划线。

Being that typescript syntax seems to be recognised automatically by the IDE and yet creates the fields in this way, leaves me to think that this is a best practice, but I have also read that this should not be done.

由于打字稿语法似乎被 IDE 自动识别,但仍以这种方式创建字段,这让我认为这是最佳实践,但我也读到不应该这样做。

Why does the IDE do this? And should I allow it to do this for an angular project? Thanks for any help!

为什么 IDE 会这样做?我应该允许它为角度项目执行此操作吗?谢谢你的帮助!

Before creating the getters and setters

在创建 getter 和 setter 之前

export class Test {


  hello:string;
  world:string;


}

After creating the getters and setters

创建 getter 和 setter 之后

export class Test {


  private _hello:string;
  private _world:string;

  get hello(): string {
    return this._hello;
  }

  set hello(value: string) {
    this._hello = value;
  }

  get world(): string {
    return this._world;
  }

  set world(value: string) {
    this._world = value;
  }
}

回答by Max Koretskyi

The getter/setter cannot have the name that matches the property name - the following won't work:

getter/setter 的名称不能与属性名称匹配 - 以下将不起作用:

class A {
   get world() {
      return this.world;
   }
}

So the general pattern is to name the internal properties just like a setter/getter only with the edition of an underscore:

所以一般的模式是像 setter/getter 一样命名内部属性,只使用下划线的版本:

class A {
   get world() {
      return this._world;
   }
}

Since JS and therefore TS lacks runtime encapsulation, an underscore usually signifies internal/private/encapsulated property/variable.

由于 JS 和 TS 缺乏运行时封装,下划线通常表示内部/私有/封装的属性/变量。

But nothing forces you to use underscores. If you name your getter/setter differently, you can avoid adding underscores:

但是没有什么会强迫您使用下划线。如果您以不同的方式命名 getter/setter,则可以避免添加下划线:

class A {
   get getWorld() {
      return this.world;
   }
}   

回答by lena

You can specify a different prefix to be used for fields in Settings | Editor | Code Style | TypeScript | Code Generation, Naming conventions/Field prefix. But note that leaving the prefix empty will result in TS2300:Duplicate identifiererrors

您可以指定要用于场不同的前缀Settings | Editor | Code Style | TypeScript | Code GenerationNaming conventions/Field prefix。但请注意,将前缀留空会导致TS2300:Duplicate identifier错误