frielmv
frielmv

Reputation: 140

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.

Upvotes: 0

Views: 556

Answers (2)

Bergi
Bergi

Reputation: 665361

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

Upvotes: 1

code
code

Reputation: 6349

You can simply return the value from the other function:

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

and

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

Upvotes: 1

Related Questions