Regrettably, the only options available to you are basic methods like Object.assign
. If your goal is to eliminate the repetition of entering parameters twice (in both the constructor signature and assignment), there isn't much more you can do.
However, you could implement a workaround like this example below. Although, the complexity and slight obfuscation it introduces may not be worthwhile in the end.
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'
In this approach, you utilize a single array containing argument names, then reference that same array when setting the properties on your instance of Something
. This method could be particularly useful in an Angular application where preserving dependency names during minification is important by utilizing the $inject
property.
Something.$inject = dependencies;
PS - Welcome to the redundant labyrinth of traditional languages that I assumed I had escaped when transitioning to JS development :P
Realistically, using a classic object literal might be a simpler solution unless the formal structure of a true class is essential.
Edit: Alternatively, if you prefer the simplicity of an object literal combined with the formality of a class, you could consider accepting an object literal in your constructor.
class Something {
constructor(params) {
Object.keys(params).forEach((name) => this[name] = params[name]);
}
}
var something = new Something({
param1: 'foo',
param2: 'bar',
param3: 'baz'
});
Although, now your class has essentially transformed into a dynamic entity that can be instantiated with any properties, resembling an object literal :P
Typically, the choice to use a class is rooted in the desire to formalize the object and provide a consistent, rigorously testable API.