Dan*_*Dan 16 intellij-idea typescript angular
我正在构建一个Angular4项目并使用IntelliJ.每当我创建一个新类,然后添加getter和setter.IDE会向字段添加下划线.
由于这种打字稿语法似乎被IDE自动识别,然后以这种方式创建字段,让我认为这是一种最佳实践,但我也读到这不应该这样做.
为什么IDE会这样做?我是否应该允许它为角度项目执行此操作?谢谢你的帮助!
在创建getter和setter之前
export class Test {
hello:string;
world:string;
}
Run Code Online (Sandbox Code Playgroud)
创建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;
}
}
Run Code Online (Sandbox Code Playgroud)
Max*_*kyi 20
getter/setter不能具有与属性名称匹配的名称 - 以下内容不起作用:
class A {
get world() {
return this.world;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,一般模式是将内部属性命名为setter/getter,仅使用下划线的版本:
class A {
get world() {
return this._world;
}
}
Run Code Online (Sandbox Code Playgroud)
由于JS因此缺乏运行时封装,因此下划线通常表示内部/私有/封装的属性/变量.
但没有什么能迫使你使用下划线.如果您以不同方式命名getter/setter,则可以避免添加下划线:
class A {
get getWorld() {
return this.world;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11142 次 |
最近记录: |