Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; 
like image 458
Vladimir Venegas Avatar asked Dec 06 '16 03:12

Vladimir Venegas


1 Answers

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 
like image 197
choz Avatar answered Sep 21 '22 10:09

choz