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

190
Views
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 answers
Answer question

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 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!