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

193
Vistas
Use overwritten value in parent constructor

I'm invoking a function in constructor where I want to use the variable from child in the function call that's made through parent constructor. For demo purpose I've created a small script to show what I want to do:

 class A{
    intVal = 1;
    constructor() {
     this.identifyClass();   
    }
    identifyClass()
    {
        console.log("I am class A", this.intVal); // This should be the value that B has overwitten
    }
}

class B extends A
{
    intVal = 2;
}

const x = new B();

So I'd want that the function in parent constructor should use the value that was overwritten by B ie. intVal = 2 but currently it uses the original value. Can I use any workaround for this so that I don't have to create a constructor in B and then invoke the function there?

Note: It's a very complex app where I don't want breaking changes to A which is being used at a lot of places and the Class B is being exposed to public so I don't want the people using Class B to change anything if possible where currently they just overwrite the instance variable

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Ok, I think I got it. We create a symbol, if the last argument passed to the constructor is not the symbol, then we create a new object, using this.constructor, passing in the original arguments, plus the symbol, and then call identify. This effectively separates the call to identify from the constructor, allowing us to get this.intVal from the subclass, while still being transparent to the user of the subclass.

const _sym = Symbol();

class A {
     intVal = 1;
     constructor() {
         const args = Array.from(arguments);
         const _ = args[args.length - 1];
         if (_ !== _sym) {
             args.push(_sym);
             const el = new this.constructor(...args);
             el.identify();
             return el;
         }
     }
     
     identify() {
         console.log(this.intVal);
     }
}

class B extends A {
    intVal = 2;
}


const x = new A();
const y = new B();

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