Home > Blockchain >  Defining multiple names for the same getter/setter function in a JavaScript class
Defining multiple names for the same getter/setter function in a JavaScript class

Time:03-01

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.

CodePudding user response:

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

CodePudding user response:

You can simply return the value from the other function:

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

and

static set anotherName(value) {
  this.name = value;
}
  • Related