Correct way of defining a model in Ionic 3

ε祈祈猫儿з 提交于 2019-12-08 00:25:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!