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

212
Visualizações
Defining multiple names for the same getter/setter function in a JavaScript class

How can I assign multiple names to the same getter/setter function inside a JS class? I know I can just do something like this:

class Example
{
    static #privateVar = 0;

    static get name(){ /* code and stuff */ return this.#privateVar; }
    static get anotherName(){ /* code and stuff */ return this.#privateVar; }

    static set name(value){ /* validating input values or something here */ this.#privateVar = value; }
    static set anotherName(value){ /* validating input values or something here */ this.#privateVar = value; }
}

but is there a simple way to give the same function multiple names without copying the code? I know I don't need different functions, but if someone else is using the class (or I just forget) and wants to use a different name for the function (i.e, different abbreviations, grey/gray, etc.), it would be convenient.

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

0

You can simply return the value from the other function:

static get anotherName() {
  return this.name;
}

and

static set anotherName(value) {
  this.name = value;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Use Object.getOwnPropertyDescriptor and Object.defineProperty to copy the accessors:

class Example {
    static #privateVar = 0;

    static get name(){ /* code and stuff */ return this.#privateVar; }
    static set name(value){ /* validating input values or something here */ this.#privateVar = value; }

    static {
        Object.defineProperty(this, 'anotherName', Object.getOwnPropertyDescriptor(this, 'name'));
    }
}
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