如何将来自多个 JavaScript 类的函数组合到一个对象中

How to combine functions from many javascript classes into one object

本文关键字:函数 组合 一个对象 JavaScript 何将来 将来      更新时间:2024-03-03

我有一个快速的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.userApi是一种object,但authLog undefined.我做错了什么?

毕竟,我最终做的是以下几点:

我的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();

谢谢大家的回答,但这就是我的做法,毕竟它很好用。

我认为使用...点差运算符是不正确的。尝试改用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 的性能不如属性。我认为您应该考虑对类的常用成员使用属性

我这样做了 -

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)

功能。 在智能感知中显示类 1、2 和 3 中的所有变量和函数,就好像它们来自一个类一样