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;
I would use an object literal:
I am late to the party, but it seems one aspect is missing.
NodeJs doesn't execute your module code every time you use require. It is more like a kind of stateful container, that initializes your module once and passes this instance each time you use require.
I am nodejs noobie, so don't use following without discussion with someone more mature, but I adhere for software principles, that considers using static methods evil (e.g. it is better to construct interface contracts against interfaces, not against concrete interface implementation; you just don't simply make it with static methods).
In other languages, it is usual corner stone to have some IoC container, that has all of your modules registered and solves passing of dependencies for you. Then you write everything as "Service" classes. Service class is instantiated most often only once per application life-time and every another piece of code, that requires it gets the same instance from the IoC container.
So I use something similar, without the comfort of IoC :( : Note in this example - A's constructor is called only once, althought required 3 times.
Test.ts:
A.ts:
B.ts:
C.ts:
Result:
So as You can see - no static methods. Works with instances (althought not with interfaces in this simplified example). A's constructor called only once.
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
Since in JS, everything is an object (except primitive types +
undefined
+null
). Like when you createsomeMethod
function above, you actually created a new function object that can be accessed withsomeMethod
insideMyStaticClass
object. (That's why you can access the properties ofsomeMethod
object likeMyStaticClass.someMethod.prototype
orMyStaticClass.someMethod.name
)However, if you find it more convenient to use class. ES6 now works with static methods.
E.g.
MyStaticClass.js
Main.js
An IICE (Immediately Invoked Class Expression) :
You can use the
static
keyword to define a method for a class