Published on

JavaScript Defining Classes Using Functions

Authors

Newer versions of ECMA support using the class keyword to define a class in JavaScript. But if for some reason you cannot use an implementation that supports this then you can define a class with private and public functions as follows:

function MyAwesomeClass(someDep1, someDep2) {
    this.someDep1 = someDep1;
    this.someDep2 = someDep2;

    // this is a public function
    this.somePublicFunction1(){
        // do your thing here
        someDep1.doIt();
        // ...
    }

    // this is private, it can be used by public functions
    function somePrivateFunction() {

    }
}

export default MyAwesomeClass;

To use this in another file simply import it then:

import MyAwesomeClass from './path/to/file/MyAwesomeClass';
...
const myAwesomeClass = new MyAwesomeClass(dep1, dep2);
...
myAwesomeClass.somePublicFunction();