thisissami thisissami - 28 days ago 8
Javascript Question

With ES6 Classes, is it ok to return an instantiation of that class from a static method?

class Thing {
constructor(parameter) {
if (parameter) {
this.x = parameter;
}
return this;
}

getX () {
return this.x;
}

static specialThing() {
return new Thing('Special Thing');
}
}

let thingy = Thing.specialThing();
thingy.getX(); // 'Special Thing'


I'd like to do the above in JavaScript (albeit in a more complex form). It runs fine currently when I run this code, but I feel odd about having a function within a class return an instantiated version of that class. Is there any reason not to build my code this way?

A functioning alternative to a static method is:

Thing.specialThing = () => {
return new Thing('Special Thing');
};


What are some pluses and minuses (if any) to using either one of these things? Are there any other better ways to accomplish this goal that I'm not aware of?

Answer

With ES6 Classes, is it ok to return an instantiation of that class from a static method?

Sure, that's fine and it is an accepted practice for some circumstances. It would typically be used when you want to codify into a reusable function that can be called from several places a specific way of calling a constructor and creating an object.

Your static function named specialThing is called a factory function (a regular function that creates and returns an object for you). A factory function can be either a static method like you show, a method of some other type of object or just a regular function (basically any type of function, static or not).

So, image you had four places in your code that all created the same object with the same or mostly the same arguments to a constructor. Rather than copy that code into four places, you just create a shared function that does all the common work for you and you can then use that in multiple places just like you would do for putting any other common code into a shared function. Except when you're creating and returning an object, that type of shared function has a particular name (a factory function). As I said earlier, the factory function can be any kind of function (whatever is most appropriate for your coding design) so a static method is certainly one of the acceptable ways of coding it.

Comments