Search code examples
javascriptecmascript-6ecmascript-next

How to combine functions from many javascript classes into one object


I’ve got a quick javascript question.

Say I’ve got RootFile.js

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

  get userApi() {
    return UserApi;
  }
};

and then I got UserApi.js

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

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

export default merged;

and then I got separate functionality files likeauth.js or 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.
  }
}

Now I want to be able to call:

import RootFile from './RootFile'

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

I can't get that to work, RootFile.userApi is a typeof object, but authLog is undefined. What am I doing wrong?


Solution

  • What I ended up doing after all was the following:

    My RootFile.js looks like this now:

    import UserApi from './UserApi'
    export default class RootFile {
    
        get userApi(){
            return UserApi;
        }
    };
    

    I got rid of the get because @Tim said they are not that performant.

    then my UserApi.js looks like this now:

    import * as Auth from './auth';
    import * as Profile from './profile';
    
    const merged = {
      ...Auth, 
      ...Profile 
    }
    
    export default merged;
    

    no more new.

    and then I got separate functionality files likeauth.js or profile.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;
    

    So no more classes, as @Bergi suggested.

    Now I am able to call:

    import RootFile from './RootFile'
    
    RootFile.userApi.profileLog();
    //and
    RootFile.userApi.authLog();
    

    Thank you all for your answers, but that is how I'll do it after all, it works great.