I have a Java background, I am trying to build a Node JS lib. I have a class in Java like this;
public class MyClass {
static List<String> myList = initMyList();
private String something;
public MyClass(String something) {
validate(something);
this.something = something;
}
public static String doSomething(String something) {
return doSomethingWithMyList(something);
}
public String doSomething() {
return doSomething(something);
}
private static String doSomethingWithMyList (String something) {
// do something with list ..
return something
}
}
As you can see, it has a static helper method static String doSomething takes String param and non static function String doSomething uses the instance variable, something.
So users can do either MyClass.doSomething(string) or MyClass m = new MyClass(sting); m.doSomething(). The former wouldn't do validation but the later will do the validation in the constructor.
I want to do this in Node JS. And I have this.
// construction function
function MyClass(something) {
validate(something);
this.something = something;
}
// static variable
MyClass.myList = someModule.getList();
// static function
MyClass.doSomething = function doSomething (something) {
return something;
};
// private static
MyClass._doSeomthingWithMyList = function _doSeomthingWithMyList (something) {
// do something wiht list
return something;
};
MyClass.prototype.doSomething = function doSomething() {
MyClass.doSomething(this.something);
};
module.export = MyClass;
As I am new to Node JS world, I want to make sure that this is right way to implement class with static and non static methods.
class keywordto define the class. You no longer have to directly manipulate the prototype. And, you can use thestatickeyword to define a static method.