Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda