Every time I create some class, I need to do the same boring procedure:
class Something {
constructor(param1, param2, param3, ...) {
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
...
}
}
Is there any way to make it more elegant and shorter? I use Babel, so some ES7 experimental features are allowed. Maybe decorators can help?
You can use
Object.assign
:It's an ES2015 (aka ES6) feature that assigns the own enumerable properties of one or more source objects to a target object.
Granted, you have to write the arg names twice, but at least it's a lot shorter, and if you establish this as your idiom, it handles it well when you have arguments you do want on the instance and others you don't, e.g.:
Example: (live copy on Babel's REPL):
Output:
Unfortunately, all you can do are simple things like
Object.assign
, but if you're trying to remove the redundancy of typing all the params twice (once in constructor signature and once in assignment) there isn't much you can do.That said, you could do a hack like this. Though I'm not sure the effort and modicum of obfuscation that comes with it is worth it.
This way you're using a single array of argument names, then using that same array as a reference when creating the properties on your instance of
Something
. This pattern would work well in an Angular application where you're trying to preserve dependency names through minification by setting the$inject
property.PS - Welcome to the redundant hell of classical languages that I thought I got away from when I became a JS developer :P
Honestly, you should probably just use a classic object literal unless you really need the formality of an actual class.
Edit: I suppose you could accept an object literal in your constructor if you want the ease of a literal and the formality of an actual class.
But now you've just turned a class into a dynamic class that can be instantiated with any properties, kinda like an object literal :P
Usually I want a class because I want to formalize the object and present a consistent and strictly testable API.
We could create a static method within each class that takes the
arguments
object and an array of names and returns an object that can be assigned to the new instance usingObject.assign
.Check it out using the Babel REPL.
Admittedly the addition of a method
buildArgs
means that this solution is not shorter, however the body of theconstructor
is and we also have these advantages:The code above accommodates extra arguments (
i >= paramNames.length
) however we could modify it if this behaviour is undesirable such that these are still parsed, but not assigned to the instance:Or ignored altogether: