How create static functions/objects in javascript/nodejs (ES6)
Solution 1
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
Solution 2
I would use an object literal:
const myObject = {
someMethod() {
// do stuff here
}
}
module.exports = myObject;
Solution 3
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());
Related videos on Youtube
Vladimir Venegas
Updated on July 09, 2022Comments
-
Vladimir Venegas almost 2 years
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;
-
Estus Flask over 7 yearsThen you don't need a class. You need an object.
-
-
ChrisG over 7 yearsShouldn't this be
someMethod: function() { }
? Edit: I see, thanks -
mattias over 7 yearsthat's method definition with ECMAScript6. Check out developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
PMV over 7 yearsIt's important to note that even in ES6 classes, prototype-based inheritance is still in full effect - the new "classes" are syntactic sugar that make prototype-based inheritance use more of the familiar syntax of classical inheritance. JavaScript objects aren't patterned from classes, they are patterned by saying "I'm like that object over there except for these differences".
-
Mulan over 7 years@ChrisG ES6 offers a new syntax