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.
var dependencies = ['param1', 'param2', 'param3'];
class Something {
constructor(...params) {
params.forEach((param, index) => this[dependencies[index]] = param);
}
}
var something = new Something('foo', 'bar', 'baz');
// something.param1 === 'foo'
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.
Something.$inject = dependencies;
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.
class Something {
constructor(params) {
Object.keys(params).forEach((name) => this[name] = params[name]);
}
}
var something = new Something({
param1: 'foo',
param2: 'bar',
param3: 'baz'
});
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.