简体   繁体   中英

Angular2 what's the benefit using getter method

I can see some examples on the internet that's using getter method.

something like this,

setId(id: number) {
    this._id = id;
}

get id() {
    return this._id;
}

What're the benefits using that? beside using getId()

The most common case is not the getter, that's rather a side effect, but the setter allows to execute code (valdiation or similar) when the value is updated.

A common getter example is also fullName where you store first name and last name in two different fields and fullName just returns ${this.firstName} ${this.lastName} .

What you can do with getter and setter can be done with methods as well, but having properties with getters and setters that can be used like simple fields, where it's not obvious there is calculation going on seem more natural.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM