Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

336
Views
JavaScript: Is there an equivalent to the Python setattr() function?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!