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

JS: this.constructor shorthand (calling static methods from non-static)

I have a JS class with utility static methods. Consider the following case:

class A{
    static util(){
        //do something
    }
    some_method(){
        //cumbersome
        this.constructor.util();
    }
};

class B extends A{
    static util(){
        //overrides super.util
        //does something different
    }
};

I’m using static method as a means to manage util functions, since it is easily overridable within an extended subclass. But the problem is that the way to access them is rather lengthy. Is there a shorthand, or a creative way to make it more manageable?

Instead of using static methods, I could resort to re-writing all the affected methods in the subclass and swap all the util functions, but that would be a shotgun surgery and will result in a very unmanageable code, so I want to avoid that as much as possible.

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 :

You could make a more concise alias for constructor at the parent class level. Not sure if this is enough of an improvement to make it worthwhile…

class A {
  static util() {
    console.log('a')
  }

  static otherUtil() {
     console.log('not overridden');
  }

  get klass() {
    return this.constructor;
  }

  some_method() {
    // less cumbersome??
    const klass = this.klass;
    klass.util();
    klass.otherUtil();
  }
};

class B extends A {
  static util() {
    console.log('b')
  }
};

let b = new B()
b.some_method()
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