Angular 有效/可能为';在TypeScript的构造函数中,s被声明为公共的?
如果我有这样一门课:Angular 有效/可能为';在TypeScript的构造函数中,s被声明为公共的?,angular,typescript,Angular,Typescript,如果我有这样一门课: export class Thing{ constructor(private some: string) { ... } get thing() { return this.some; } set thing(value: string) { this.some = value; } } 我想知道这是否是一种适当的方法,可以使用可从构造函数分配的支持字段来拥有受控属性(通过get和set)。有没有更简单的方法 当然,其中一种方法是: export clas
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) { ... }
}
但在最初阶段,我们只能控制set。另一个是:
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) { ... }
}
如果您需要在get和set中执行自定义代码,并且还希望使用不同的支持字段,那么我看不出它如何比第一种情况简单得多。如果您只是试图阻止用户设置公共字段,则可以将其标记为只读(带有警告)。我对您试图简化的内容感到困惑。@jcalz我碰巧发现,我可以将构造函数的参数设置为公共参数,使其成为属性。早些时候,我错误地发现,不在方法声明上设置public/void意味着它们隐式存在。喜欢简洁的语法,我总是问自己我的代码是否可以改进。遗憾的是,从你的评论来看,在这种情况下,答案是“不”。这确实是有目的的。我只是为了简明扼要而省略了它。@KonradViltersten我想可能是这样:)