Home > Software design >  Is there a way to reference "the current class" from a Javascript class method
Is there a way to reference "the current class" from a Javascript class method

Time:01-06

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?

CodePudding user response:

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

  •  Tags:  
  • Related