代码之家  ›  专栏  ›  技术社区  ›  slipperypete

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

  •  34
  • slipperypete  · 技术社区  · 7 年前

    角度4 IntelliJ公司 。每当我创建一个新类,然后添加 吸气剂 二传手 。IDE在字段中添加下划线。

    由于类型脚本语法似乎被IDE自动识别,但却以这种方式创建字段,这让我认为这是一种最佳实践,但我也读到了不应该这样做的内容。

    IDE为什么这样做?我应该允许它对角度项目这样做吗?谢谢你的帮助!

    在创建getter和setter之前

    export class Test {
    
    
      hello:string;
      world:string;
    
    
    }
    

    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;
      }
    }
    
    2 回复  |  直到 7 年前
        1
  •  40
  •   Max Koretskyi    7 年前

    getter/setter的名称不能与属性名称匹配-以下操作无效:

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

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

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

    class A {
       get getWorld() {
          return this.world;
       }
    }   
    
        2
  •  2
  •   lena    7 年前

    可以为中的字段指定不同的前缀 Settings | Editor | Code Style | TypeScript | Code Generation Naming conventions/Field prefix 。但请注意,保留前缀为空将导致 TS2300:Duplicate identifier 错误