Every time I create some class, I need to do the same boring procedure:
class Something {
constructor(param1, param2, param3, ...) {
this.param1 = para
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 using Object.assign.
Check it out using the Babel REPL.
class Something {
static buildArgs (ctx, args, paramNames) {
let obj = {}
Array.from(args).forEach(function (arg, i) {
let name = paramNames[i] || i
obj[name] = args[i]
})
Object.assign(ctx, obj)
}
constructor () {
Something.buildArgs(this, arguments, [
'param1',
'param2'
]);
console.log(this)
}
}
new Something('one', 'two')
Admittedly the addition of a method buildArgs means that this solution is not shorter, however the body of the constructor 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:
class Something {
static buildArgs (ctx, args, paramNames) {
let obj = {instance: {}, extra: {}}
Array.from(args).forEach(function (arg, i) {
let name = paramNames[i] || i
if (name) {
obj.instance[name] = args[i]
} else {
obj.extra[i] = args[i]
}
})
Object.assign(ctx, obj)
}
constructor () {
let args = Something.buildArgs(this, arguments, ['param1', 'param2']);
// Do stuff with `args.extra`
}
}
Or ignored altogether:
static buildArgs (args, paramNames) {
let obj = {}
Array.from(args).forEach(function (arg, i) {
let name = paramNames[i]
if (name) obj[name] = args[i]
})
return obj
}