首页 > 解决方案 > Javascript - 将类重构为 JS 对象

问题描述

我正在将我当前的 Firebase 类拆分为更小的片段。

export default class Firebase {
  constructor() {
    if (!firebase.apps.length) {
      // Initialize App
      firebase.initializeApp(Constants.manifest.web.config.firebase);

      // Initialize APIs
      this._usersAPI = new Users();
      this._contentAPI = new Content();
      this._messagingAPI = new Messaging();
      this._notificationsAPI = new Notifications();
    }
  }

  get usersAPI() {
    return this._usersAPI;
  }

  ...
}

如您所见,Firebase 类由较小的组成。

但是,老实说,smalle 类似乎不需要作为类来实现。

现在,我正在考虑将它们移至 JS 对象

export default class Auth {
  constructor() {
    this.auth = firebase.auth();
    this.firestore = firebase.firestore();
  }

  /*
    Persistance
  */

  enableAuthPersistence() {
    return this.auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
  }

  /*
    Sign in/out
  */

  signInWithEmailAndPassword(email, password) {
    return this.auth.signInWithEmailAndPassword(email, password);
  }

  async signInWithUsernameAndPassword(username, password) {
    ...
  }

  signOut() {
    return this.auth.signOut();
  }

  /*
    Password
  */

  resetPassword(email) {
    return this.auth.sendPasswordResetEmail(email);
  }

  updatePassword(password) {
    return this.auth.currentUser.updatePassword(password);
  }

  /*
    Helpers
  */

  parseError(errorCode) {
    ...
  }

  get currentUser() {
    return this.auth.currentUser;
  }
}

如何将它们转换为对象?所以我做

  import users from "./api/users";
 
  ...


  constructor() {
     ...
     // Initialize APIs
     this._usersAPI = users;
     this._contentAPI = content;
     this._messagingAPI = messaging;
     this._notificationsAPI = notifications;
  }

  ...

在我的 Firebase 类中,而不是实例化?

标签: javascriptoopecmascript-6refactoring

解决方案


您只需将通常在构造函数中初始化的内容作为对象字面量的属性,所有方法和 getter/setter 与速记方法和 getter/setter 类似地放在同一个对象字面量上:

export default {
  auth: firebase.auth(),
  firestore: firebase.firestore(),

  /*
    Persistance
  */
  enableAuthPersistence() {
    return this.auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
  },

  /*
    Sign in/out
  */
  signInWithEmailAndPassword(email, password) {
    return this.auth.signInWithEmailAndPassword(email, password);
  },

  async signInWithUsernameAndPassword(username, password) {
    ...
  },

  signOut() {
    return this.auth.signOut();
  },

  /*
    Password
  */
  resetPassword(email) {
    return this.auth.sendPasswordResetEmail(email);
  },
  updatePassword(password) {
    return this.auth.currentUser.updatePassword(password);
  },

  /*
    Helpers
  */
  parseError(errorCode) {
    ...
  },
  get currentUser() {
    return this.auth.currentUser;
  },
};

改变的只是元素之间的class, theconstructor和一些逗号。


推荐阅读