Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

335
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda