I have a class to which I would like to include a method of overriding some of the default instance variables in the constructor, without having a dozen parameters. I would like to do this by passing an object in the form of:
JavaScript
x
16
16
1
class MyClass {
2
constructor(overrides) {
3
this.instanceVar1 = default1;
4
this.instanceVar2 = default2,
5
6
for (key in overrides) {
7
this.key = overrides[key];
8
}
9
}
10
11
let overrides = {instanceVar1 : value,
12
instanceVar2 : value2};
13
let instance = new MyClass(overrides);
14
15
console.log(instance.instanceVar1) // Outputs value, not default1.
16
In Python this could be done with
JavaScript
1
4
1
if overrides is not None:
2
for key, value in overrides.items():
3
self.setattr(self, key, value)
4
Is there a JS equivalent or do I just have to add a bunch of parameters with default values?
Advertisement
Answer
For your given example you simply need to use bracket notation to access a property from a variable.
JavaScript
1
19
19
1
class MyClass {
2
constructor(overrides) {
3
this.instanceVar1 = 'default1';
4
this.instanceVar2 = 'default2';
5
6
for (const key in overrides) {
7
this[key] = overrides[key];
8
// ^^^
9
}
10
}
11
}
12
13
let overrides = {
14
instanceVar1: 'value',
15
instanceVar2: 'value2'
16
}
17
let instance = new MyClass(overrides);
18
19
console.log(instance.instanceVar1); // value
An alternative would be to destructure the needed parameters from the overrides
object setting appropriate defaults, and leaving the ...rest
for use elsewhere.
JavaScript
1
21
21
1
class MyClass {
2
constructor({
3
instanceVar1 = 'default1',
4
instanceVar2 = 'default2',
5
overrides
6
}) {
7
this.instanceVar1 = instanceVar1;
8
this.instanceVar2 = instanceVar2;
9
10
console.log(overrides); // { extraVar1: 'another value' }
11
}
12
}
13
14
let overrides = {
15
instanceVar1: 'value',
16
instanceVar2: 'value2',
17
extraVar1: 'another value'
18
}
19
let instance = new MyClass(overrides);
20
21
console.log(instance.instanceVar1); // value