【发布时间】:2016-07-28 14:21:53
【问题描述】:
我有一个快速的 JavaScript 问题。
说我有RootFile.js
import UserApi from './UserApi'
export default class RootFile {
get userApi() {
return UserApi;
}
};
然后我得到了UserApi.js
import Auth from './auth';
import Profile from './profile';
const merged = {
...new Auth,
...new Profile
}
export default merged;
然后我得到了单独的功能文件,例如auth.js 或profile.js。
auth.js
export default class Auth{
authLog(){
console.log("DONE");
//Gotta find a way to run this.
}
}
profile.js
export default class Profile{
profileLog(){
console.log("DONE");
//Gotta find a way to run this.
}
}
现在我希望能够打电话:
import RootFile from './RootFile'
RootFile.userApi.profileLog();
//and
RootFile.userApi.authLog();
我无法让它工作,RootFile.userApi 是 object 的类型,但 authLog 是 undefined。
我做错了什么?
【问题讨论】:
-
profileLog和authLog是 继承 方法,不会被Object.assign或属性扩展运算符复制。但是,您实际上并不真正想要将多个彼此无关的类组合在一个对象中。如果它们应该是可组合的,则将它们设为 mixin。 -
@Bergi 你能写一个答案来解释这样做的正确方法吗?
-
我什至不确定您为什么要这样做,所以我不知道“正确”的方式是什么。这些东西应该是单例吗?如果没有
class,你会怎么写? -
你看也许它们不一定是类,我真正想要实现的是,有一组与配置文件有关的函数,另一组与auth,另一组与其他事情有关的函数等等。我最终希望实现的是能够以一种干净的方式从我的
UserApi引用所有这些函数,而不必为每个函数编写单独的 getter的功能。来自 C++、Java 和 Objective-C,没有类的 JavaScript 对我来说总是很奇怪,所以也许这就是我感到困惑的原因。
标签: javascript ecmascript-6 ecmascript-next