javascript - 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 类中,而不是实例化?
解决方案
您只需将通常在构造函数中初始化的内容作为对象字面量的属性,所有方法和 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
和一些逗号。
推荐阅读
- apache-spark - 为不同实体填补时间序列 Spark 中的空白
- java - 查找和更改元组值
- python - 没有名为“oauth2_provider.ext”的模块
- slatejs - Slatejs 如何使一个特定节点不可编辑?
- php - 找不到列,因为我的表中有不同的列名
- android - 如何将 webapp 和 android 应用与 firebase 连接?
- python - 使用 requests.get 从商店网站查找简单的产品信息
- php - 如何使用 XAMPP 启动 apache 服务器?
- abap - 想要显示结果列表中的所有行项目而不是最后一个行项目
- java - 如何将基于 JAVA6 EJB 的应用程序迁移到 OpenJDK 13?