问题
What is the correct way of defining a model in Ionic 3 with getters and setters?
I followed this.
export class ItemModel{
private _name: string;
constructor(private n: string){
this._name = n;
}
get name(): string
{
return this._name;
}
set name(name: string)
{
this._name = name;
}
}
Is it correct?
In some forums it was mentioned about a need to keep the code very short. So does that mean using getters and setters would affect the performance somehow?
回答1:
Typescript supports accessors natively, which effectively handle the job of getters and setters. You don't need to manually define them as separate methods.
回答2:
With typescript, you can just define it like below.You don't need to do big work.Typescript will do the rest.
TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object.
export class ItemModel {
name: string;
note: string;
}
let itemModel = new ItemModel();
itemModel.name= "My Name";
来源:https://stackoverflow.com/questions/47215565/correct-way-of-defining-a-model-in-ionic-3