How create static functions/objects in javascript/nodejs (ES6)

Vladimir Venegas picture Vladimir Venegas · Dec 6, 2016 · Viewed 30.9k times · Source

I want to create a static class using Javascript/Node JS. I used google but i can't find any usefull example.

I want to create in Javascript ES6 something like this (C#):

public static MyStaticClass {
   public static void someMethod() {
      //do stuff here
   }
}

For now, I have this class, but I think that this code will creates a new instance every time that it be called from "require".

function MyStaticClass() {
   let someMethod = () => {
      //do some stuff
   }
}
var myInstance = new MyStaticClass();
module.exports = factory;

Answer

choz picture choz · Dec 6, 2016

Note that JS is prototype-based programming, instead of class-based.

Instead of creating the class multiple times to access its method, you can just create a method in an object, like

var MyStaticClass = {
    someMethod: function () {
        console.log('Doing someMethod');
    }
}

MyStaticClass.someMethod(); // Doing someMethod

Since in JS, everything is an object (except primitive types + undefined + null). Like when you create someMethod function above, you actually created a new function object that can be accessed with someMethod inside MyStaticClass object. (That's why you can access the properties of someMethod object like MyStaticClass.someMethod.prototype or MyStaticClass.someMethod.name)

However, if you find it more convenient to use class. ES6 now works with static methods.

E.g.

MyStaticClass.js

class MyStaticClass {
    static someMethod () {
        console.log('Doing someMethod');
    }

    static anotherMethod () {
        console.log('Doing anotherMethod');
    }
}

module.exports = MyStaticClass;

Main.js

var MyStaticClass = require("./MyStaticClass");

MyStaticClass.someMethod(); // Doing someMethod
MyStaticClass.anotherMethod(); // Doing anotherMethod