Home > database >  JavaScript: Is there an equivalent to the Python setattr() function?
JavaScript: Is there an equivalent to the Python setattr() function?

Time:06-06

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:

class MyClass {
    constructor(overrides) {
        this.instanceVar1 = default1;
        this.instanceVar2 = default2,

        for (key in overrides) {
           this.key = overrides[key];
        }
    }

let overrides = {instanceVar1 : value,
                 instanceVar2 : value2};
let instance = new MyClass(overrides);

console.log(instance.instanceVar1)  // Outputs value, not default1.

In Python this could be done with

if overrides is not None:
    for key, value in overrides.items():
        self.setattr(self, key, value)

Is there a JS equivalent or do I just have to add a bunch of parameters with default values?

CodePudding user response:

For your given example you simply need to use bracket notation to access a property from a variable.

class MyClass {
  constructor(overrides) {
    this.instanceVar1 = 'default1';
    this.instanceVar2 = 'default2';

    for (const key in overrides) {
      this[key] = overrides[key];
      //   ^^^
    }
  }
}

let overrides = {
  instanceVar1: 'value',
  instanceVar2: 'value2'
}
let instance = new MyClass(overrides);

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.

class MyClass {
  constructor({
    instanceVar1 = 'default1',
    instanceVar2 = 'default2',
    ...overrides
  }) {
    this.instanceVar1 = instanceVar1;
    this.instanceVar2 = instanceVar2;

    console.log(overrides); // { extraVar1: 'another value' }
  }
}

let overrides = {
  instanceVar1: 'value',
  instanceVar2: 'value2',
  extraVar1: 'another value'
}
let instance = new MyClass(overrides);

console.log(instance.instanceVar1); // value

  • Related