【发布时间】:2017-12-23 08:18:43
【问题描述】:
我正在构建一个 Angular4 项目并使用 IntelliJ。每当我创建一个新类,然后添加 getters 和 setters。 IDE 为字段添加下划线。
因为打字稿语法似乎被 IDE 自动识别,但以这种方式创建字段,让我认为这是一种最佳实践,但我也读到不应该这样做。
IDE 为什么要这样做?我应该允许它为一个有角度的项目做这个吗?感谢您的帮助!
在创建 getter 和 setter 之前
export class Test {
hello:string;
world:string;
}
在创建 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;
}
}
【问题讨论】:
-
你能发布一个代码示例吗?
-
@Maximus 我添加了一个代码示例,变量_hello 在我添加getter 和setter 之前是hello。
-
私有变量以
_开头,仅此而已 -
可能值得注意的是,如果你有一个 json 对象
const json = { "hello": "foo", "world": "bar" }和const baz = new Test()那么你可以只做Object.assign(baz, json)它将调用设置器并正确分配给私有_hello和 @ 987654328@ 属性。
标签: angular typescript intellij-idea