如何在 JS 類中為同一個 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; }
}
但是有沒有一種簡單的方法可以在不復制代碼的情況下給同一個函式多個名稱?我知道我不需要不同的功能,但是如果其他人正在使用該類(或者我只是忘記了)并且想要為該功能使用不同的名稱(即不同的縮寫,灰色/灰色等),它會方便。
uj5u.com熱心網友回復:
使用Object.getOwnPropertyDescriptor和Object.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'));
}
}
uj5u.com熱心網友回復:
您可以簡單地從另一個函式回傳值:
static get anotherName() {
return this.name;
}
和
static set anotherName(value) {
this.name = value;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/435748.html
標籤:javascript 班级
