Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

If I understood what you need, you can create a constructor for each class and bind its own util function to a class attribute called _util. Then you can just do this._util():

class A{
    constructor() {
      this._util = A.util
    }
    
    static util(){
        console.log("util A")
    }
    some_method(){
        this._util();
    }
};

class B extends A{
    constructor() {
      super();
      this._util = B.util
    }
    
    static util(){
        console.log("util B")
    }
};


new A().some_method()
new B().some_method()

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda