How create static functions/objects in javascript/nodejs (ES6)
You can use the static
keyword to define a method for a class
class MyStatisticsClass {
static someMethod() {
return "MyStatisticsClass static method"
}
}
console.log(MyStatisticsClass.someMethod());
I would use an object literal:
const myObject = {
someMethod() {
// do stuff here
}
}
module.exports = myObject;
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