如果我有这样的类:
export class Thing{
constructor(private some: string) { ... }
get thing() { return this.some; }
set thing(value: string) { this.some = value; }
}
我想知道这是否是使用可从构造函数分配的后备字段的受控属性(通过get和set(的正确方法。有一个简单的方法吗?
当然,一种方法是这样做的:
export class Thing{
constructor(public some: string) { ... }
}
,但是我们只能控制初始阶段。另一个是:
export class Thing{
constructor(private some: string) { ... }
}
,但随后我们无法公开访问它。并且仅使用set/get可以在创建对象时无法设置。
您已经在问题中以正确的方式做到了,假设您将使用Getter和setter出于目的:
export class Thing {
constructor(private some: string) { ... }
get thing() { return this.some; }
set thing(value: string) { this.some = value; }
}
如果您的Getter和Setter确实像此示例一样简单,那么您的其他示例几乎没有好处:
export class Thing {
constructor(public thing: string) { ... }
}