在 JavaScript class 中为同一个 getter/setter 函数定义多个名称

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

如何为 JS class 中的同一个 getter/setter 函数分配多个名称?我知道我可以做这样的事情:

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

但是有没有一种简单的方法可以在不复制代码的情况下为同一个函数赋予多个名称?我知道我不需要不同的功能,但是如果其他人正在使用 class(或者我只是忘记了)并且想为该功能使用不同的名称(即不同的缩写,grey/gray,等),这样会很方便。

您可以简单地 return 来自其他函数的值:

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

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

使用Object.getOwnPropertyDescriptorObject.defineProperty复制存取器:

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