如何将许多 javascript 类 中的函数组合到一个对象中

How to combine functions from many javascript classes into one object

我有一个快速的 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.jsprofile.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.userApiobject 的类型,但 authLogundefined。 我做错了什么?

我认为 ... 展开运算符的使用不正确。尝试改用 Object.assign - 它接受一个目标对象并将其他对象的所有可枚举属性分配给它。

import Auth from './auth';
import Profile from './profile';

let merged = {};
Object.assign(merged, new Auth, new Profile);

export default merged;

我认为你不想那样做。在它们各自的 类 中分离逻辑的全部意义在于获得一个结构更清晰、更易于维护的库。

我会选择作文:

export default class RootFile  {

  get userApi() {
    // Some logic here?

    // Just return a newly created api for now:
    return new UserApi;
  }
};

UserApi做同样的事情:

export default class UserApi {

  get profile() {
    return new Profile;
  }
};

并像这样使用它:

rootFile.userApi.profile.log("etc");

为什么要作文?

  • 这样你就不用担心函数的重新定义了。
  • 速度更快,JavaScript 引擎现在可以针对您的 类 进行优化,而这对于合并结构是不可能的。

另请记住,getter 的性能不如属性。我认为您应该考虑为 类

的常用成员使用属性

最终我做了以下事情:

我的 RootFile.js 现在看起来像这样:

import UserApi from './UserApi'
export default class RootFile {

    get userApi(){
        return UserApi;
    }
};

我摆脱了 get 因为@Tim 说他们的表现不佳。

那么我的 UserApi.js 现在看起来像这样:

import * as Auth from './auth';
import * as Profile from './profile';

const merged = {
  ...Auth, 
  ...Profile 
}

export default merged;

没有了 new.

然后我得到了单独的功能文件,如auth.jsprofile.js

auth.js

export function authLog(){
    console.log("auth test ");
},
export default auth;

profile.js

export function profileLog(){
    console.log("profile test ");
} 
export default profile;

所以不再 类,正如@Bergi 建议的那样。

现在我可以打电话了:

import RootFile from './RootFile'

RootFile.userApi.profileLog();
//and
RootFile.userApi.authLog();

谢谢大家的回答,但毕竟我会这样做,效果很好。

我这样做了 -

import { One } from './one.js'
import { Two } from './two.js'
import { Three } from './three.js'

const MasterClazz2 = {
    ...new One(),
    ...new Two(),
    ...new Three()
}

export default MasterClazz2

然后我这样导入-

import func from './combinedClazz.js'

func.oneFunc()
func.threeFunc()
func.threeFunc()
func.threeNameFunc('Sebastian')

console.log('variable: ' + func.one)
console.log('variable: ' + func.two)
console.log('variable: ' + func.three)

功能。在智能感知中显示来自 classes 一、二和三的所有变量和函数,就好像它们来自一个 class