Use overwritten value in parent constructor

Viewed 55

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

1 Answers

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();

Related