TS与JS中的Getters和Setter究竟有什么用?

摘要:在本文中,我们讨论了getter 和 setter 在现代 Web 开发中的实用性。它们有用吗?什么时候使用它们是有意义的?尽管我不同意 getter 和 setter 完全是一个反模式。但它们在几种情况下能带来更多的实用性。

在本文中,我们讨论了getter 和 setter 在现代 Web 开发中的实用性。它们有用吗?什么时候使用它们是有意义的?

当 ECMAScript 5(2009)发布时,getters 和 setter(也称为访问器)被引入 JavaScript。问题是,对于引入它们的原因及实用性存在很多困惑。

我在 reddit 看到了一个帖子【 https://www.reddit.com/r/typescript/comments/87t1h7/are_getters_and_setters_an_antipattern/ 】,讨论的内容是它们是否是反模式。不幸的是,该主题的普遍共识是 “yes”。我认为这是因为大多数情况下,你所做的前端编程都不会要求提供 getter 和 setter 这样的操作。尽管我不同意 getter 和 setter 完全是一个反模式。但它们在几种情况下能带来更多的实用性。


它们是什么?

getter 和 setter 是另一种提供对象属性访问的方法。

一般的用法如下所示:

interface ITrackProps {
  name: string;
  artist: string;
}

class Track {  
  private props: ITrackProps;

  get name (): string {
    return this.props.name;
  }

  set name (name: string) {
	  this.props.name = name;
  }

  get artist (): string {
    return this.props.artist;
  }

  set artist (artist: string) {
	  this.props.artist = artist;
  }

  constructor (props: ITrackProps) {
    this.props = props;
  } 

  public play (): void {	
	  console.log(`Playing ${this.name} by ${this.artist}`);
  }
}

现在问题变成了:“为什么不只使用常规类属性?”

那么,在这种情况下, 是可以的 。

interface ITrackProps {
  name: string;
  artist: string;
}

class Track {  
  public name: string;
  public artist: string;

  constructor (name: string, artist: string;) {
    this.name = name;
    this.artist = artist;
  } 

  public play (): void {	
	  console.log(`Playing ${this.name} by ${this.artist}`);
  }
}

这是一个非常简单的例子,让我们来看一个更好地描述,为什么我们应该关心使用 getter 和 settter 与常规类属性的场景。


防止贫血模式

你还记得贫血模式(译者注:一种反模式)是什么吗?尽早发现贫血模式的方法之一是,假如你的域实体的 每个属性 都有getter和setter(即: set 对域特定语言没有意义的操作)暴露的话。

如果你没有明确地使用 get 或 set 关键字,那么会使所有 public 也有相同的负面影响。

思考这个例子:

class User {
  // Bad. You can now `set` the user id.
  // When would you ever need to mutate a user's id to a
  // different identifier? Is that safe? Should you be able to?
  public id: UserId;

  constuctor (id: UserId) {
    this.id = id;
  }
}

在领域驱动设计中,为了防止出现贫血模式,并推进特定于领域的语言的创建,对于我们 仅公开对领域 有效的操作非常重要。

这意味着你需要了解自己正在工作的领域【 https://khalilstemmler.com/articles/solid-principles/single-responsibility/ 】。

我会让自己接受审查。让我们来看看 White Label 【 https://github.com/stemmlerjs/white-label】中的 Vinyl 类,这是一个开源的乙烯基交易程序,使用领域驱动进行设计并基于 TypeScript 构建。

import { AggregateRoot } from "../../core/domain/AggregateRoot";
import { UniqueEntityID } from "../../core/domain/UniqueEntityID";
import { Result } from "../../core/Result";
import { Artist } from "./artist";
import { Genre } from "./genre";
import { TraderId } from "../../trading/domain/traderId";
import { Guard } from "../../core/Guard";
import { VinylCreatedEvent } from "./events/vinylCreatedEvent";
import { VinylId } from "./vinylId";

interface VinylProps {
  traderId: TraderId;
  title: string;
  artist: Artist;
  genres: Genre[];
  dateAdded?: Date;
}

export type VinylCollection = Vinyl[];

export class Vinyl extends AggregateRoot<VinylProps> {

  public static MAX_NUMBER_GENRES_PER_VINYL = 3;

  //  1. Facade. The VinylId key doesn't actually exist
  // as a property of VinylProps, yet- we still need
  // to provide access to it.

  get vinylId(): VinylId {
    return VinylId.create(this.id)
  }

  get title (): string {
    return this.props.title;
  }

  //2. All of these properties are nested one layer
  // deep as props so that we can control access 
  // and mutations to the ACTUAL values.

  get artist (): Artist {
    return this.props.artist
  }

  get genres (): Genre[] {
    return this.props.genres;
  }

  get dateAdded (): Date {
    return this.props.dateAdded;
  }

  //3. You'll notice that there are no setters so far because 
  // it doesn't make sense for us to be able to change any of these
  // things after it has been created

  get traderId (): TraderId {
    return this.props.traderId;
  }

  //4. This approach is called "Encapsulate Collection". We
  // will need to add genres, yes. But we still don't expose the
  // setter because there's some invariant logic here that we want to
  // ensure is enforced.
  // Invariants: 
  // https://khalilstemmler.com/wiki/invariant/

  public addGenre (genre: Genre): void {
    const maxLengthExceeded = this.props.genres
      .length >= Vinyl.MAX_NUMBER_GENRES_PER_VINYL;

    const alreadyAdded = this.props.genres
      .find((g) => g.id.equals(genre.id));

    if (!alreadyAdded && !maxLengthExceeded) {
      this.props.genres.push(genre);
    }
  }

  //5. Provide a way to remove as well.

  public removeGenre (genre: Genre): void {
    this.props.genres = this.props.genres
      .filter((g) => !g.id.equals(genre.id));
  }

  private constructor (props: VinylProps, id?: UniqueEntityID) {
    super(props, id);
  }

  // 6. This is how we create Vinyl. After it's created, all properties 
  // effectively become "read only", except for Genre because that's all that
  // makes sense to enabled to be mutated.

  public static create (props: VinylProps, id?: UniqueEntityID): Result<Vinyl> {
    const propsResult = Guard.againstNullOrUndefinedBulk([
      { argument: props.title, argumentName: 'title' },
      { argument: props.artist, argumentName: 'artist' },
      { argument: props.genres, argumentName: 'genres' },
      { argument: props.traderId, argumentName: 'traderId' }
    ]);

    if (!propsResult.succeeded) {
      return Result.fail<Vinyl>(propsResult.message)
    } 

    const vinyl = new Vinyl({
      ...props,
      dateAdded: props.dateAdded ? props.dateAdded : new Date(),
      genres: Array.isArray(props.genres) ? props.genres : [],
    }, id);
    const isNewlyCreated = !!id === false;

    if (isNewlyCreated) {
      // 7. This is why we need VinylId. To provide the identifier
      // for any subscribers to this domain event.
      vinyl.addDomainEvent(new VinylCreatedEvent(vinyl.vinylId))
    }

    return Result.ok<Vinyl>(vinyl);
  }
}

充当外观、维护只读值、强制执行模型表达、封装集合以及创建域事件【 https://khalilstemmler.com/blogs/domain-driven-design/where-do-domain-events-get-dispatched/ 】是领域驱动设计中 getter 和 setter 的一些非常可靠的用例。


在 Vue.js 中更改检测

Vue.js 是一个较新的前端框架,以其快速和响应式而闻名。Vue.js 能够如此有效地检测改变的原因是它们用 Object.defineProperty() API 去 监视 对 View Models 的更改!

来自 Vue.js 关于响应式的文档:

当你将纯 JavaScript 对象作为其数据选项传递给 Vue 实例时,Vue 将遍历其所有属性并用 Object.defineProperty 将它们转换为 getter/setter。getter/setter 对用户是不可见的,但是在幕后,它们使 Vue 能够在访问或修改属性时执行依赖关系跟踪和更改通知。——  Vue.js 文档:响应式(https://vuejs.org/v2/guide/reactivity.html)

总之,getter 和 setter 针对很多问题有很大的实用性。不过在现代前端 Web 开发中,这些问题并没有太多出现。

原文: https://www.freecodecamp.org/news/typescript-javascript-getters-and-setters-are-they-useless/


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_4108