简体   繁体   中英

Typescript: Class members initialization vs setters and getters

I have the following code:

export class Myclass {
   private _someVal = 2;

   public get someVal() {
      return this._someVal;
   }

   public set someVal(val) {
      this._someVal = val;
   }
}

I am using this someVal in the template <span>{{ someVal }}</span>

The value is not changing.

Is there any difference between using setters getters and setters, or simply having let someVal = 2 and using it directly in the template?

in this particular case there is no difference between what you've done and doing:

export class Myclass {
   someVal = 2;

}

setters and getters have use cases, such as when you need to do something else when setting a value, but this isn't one of them.

The only difference is that the get/set implementation allows you to have more flexibility, while the public property would be less flexible.

Example of what you could do with get:

export class Myclass {
   private _someVal = 2;
   private _otherVal = 1;

   public get calculatedVal() {
      return this._someVal + this._otherVal;
   }
}

And then access calculatedVal as a property like this: <span>{{ calculatedVal}}</span>

Within a class you don't use the let keyword.

In this case there is no point in using accessors. If you trigger an action on set, or compute the value on get, then it makes sense to use them.

If accessing the property directly works, it is probably the right solution.

It is common in the Java world to create getters/setters for each field in a DTOs, it is arguable whether this is an anti-pattern. This practice leaks into other languages.

Rule of thumb: if you don't need an accessor, use a property.

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