【发布时间】:2021-04-01 17:45:10
【问题描述】:
我正在将我当前的 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 类中,而不是实例化?
【问题讨论】:
-
实际上 JS 中的所有东西都在一个对象中(并非都继承自 Object)。类只是调用 Object.create() 并做一些原型设计的简单方法。也许你应该看看 js 中的静态类方法。对您的代码进行最小的更改。
-
只使用全局变量和函数,比如
let userApi = new Users(); export function getUser() { /*...*/ }等等?
标签: javascript oop ecmascript-6 refactoring