Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to reference "the current class" from a Javascript class method

I’m wondering if there’s a way to reference the "current class" rather than a class by name, from within a Javascript class.

For example:

class MyBase{
    static makeNew(id){
        const newInstance = new --currentClass--;// magic happens here
        newInstance.id = id;
        return newInstance;
    }
}

class A extends MyBase{}
class B extends MyBase{}

const newA = A.makeNew(1);
const newB = B.makeNew(379);

Is there a way for me to write MyBase::makeNew in such a way that when it’s called from the A class, it returns a new instance of A, but when called from the B class, it returns a new instance of B?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since the call signatures are like:

A.makeNew(1);
B.makeNew(379);

That might look familiar – you can use this to reference the object it’s being called on.

class MyBase{
    static makeNew(id){
        const newInstance = new this();
        newInstance.id = id;
        return newInstance;
    }
}

class A extends MyBase{}
class B extends MyBase{}

const newA = A.makeNew(1);
const newB = B.makeNew(379);

console.log(newA instanceof A);
console.log(newB instanceof B);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading