简体   繁体   English

打字稿:类成员初始化与 setter 和 getter

[英]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>我在模板<span>{{ someVal }}</span>使用了这个someVal

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?使用 setter getter 和 setter 或简单地let someVal = 2并直接在模板中使用它之间有什么区别吗?

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. setter 和 getter 都有用例,例如当您在设置值时需要做其他事情时,但这不是其中之一。

The only difference is that the get/set implementation allows you to have more flexibility, while the public property would be less flexible.唯一的区别是 get/set 实现允许您具有更大的灵活性,而 public 属性则不太灵活。

Example of what you could do with get:你可以用 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>然后像这样访问calculatedVal作为属性: <span>{{ calculatedVal}}</span>

Within a class you don't use the let keyword.在一个类中,您不使用let关键字。

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.如果你在 set 上触发一个动作,或者在 get 上计算值,那么使用它们是有意义的。

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.在 Java 世界中,为 DTO 中的每个字段创建 getter/setter 是很常见的,这是否是一种反模式是有争议的。 This practice leaks into other languages.这种做法会泄漏到其他语言中。

Rule of thumb: if you don't need an accessor, use a property.经验法则:如果您不需要访问器,请使用属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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