¿Cómo puedo asignar múltiples nombres a la misma función getter/setter dentro de una clase JS? Sé que puedo hacer algo como esto:
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; } }pero, ¿hay una forma sencilla de dar a la misma función varios nombres sin copiar el código? Sé que no necesito funciones diferentes, pero si alguien más está usando la clase (o simplemente se me olvida) y quiere usar un nombre diferente para la función (es decir, abreviaturas diferentes, gris/gris, etc.), sería ser conveniente.
Simplemente puede devolver el valor de la otra función:
static get anotherName() { return this.name; }y
static set anotherName(value) { this.name = value; }Use Object.getOwnPropertyDescriptor y Object.defineProperty para copiar los accesores:
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')); } }