Home > Software engineering >  How do I group multiple functions within one class in JavaScript?
How do I group multiple functions within one class in JavaScript?

Time:12-08

My JavaScript class module file contains multiple functions of various categories, such as file-operation related ones and string-processing related ones.

class App {
  static fileFunc1() {
    ...
  }

  static fileFunc2() {
    ...
  }

  static strFunc1() {
    ...
  }

  static strFunc2() {
    ...
  }
}

I wanted to categorize these functions within ONE FILE so that they can be called as a chained string as follows.

App.file.fileFunc1();
App.str.strFunc2();

After some trials and errors, I found the solution by myself as described below.

class App {
  /**
   * Group of file-operation related functions
   */
  static file {
    fileFunc1: () => {
      ...
    },

    fileFunc2: () => {
      ...
    }
  };

  /**
   * Group of string-processing related functions
   */
  static str {
    strFunc1: () => {
      ...
    },

    strFunc2: () => {
      ...
    }
  };
}

Is this the recommended way to achieve my needs?
Or are there any other recommended solutions or smart ideas?

[Additional remarks]

There is one thing I have to mention that I don't want to divide those functions into multiple files because there are already many generic module files and increasing the number of files is not welcome.

CodePudding user response:

A class with only static methods doesn't make much sense as a class - the primary benefit of a class is the ability to tie together persistent data with methods that operate on that data. If you never instantiate the class, consider whether a plain object would be more appropriate.

const App = {
  file: {
    fileFunc1: () => {
      // ...
    },
    fileFunc2: () => {
      // ...
    }
  },

  str: {
    strFunc1: () => {
      // ...
    },
    strFunc2: () => {
      // ...
    }
  }
};
  • Related