[英]Defining multiple names for the same getter/setter function in a JavaScript class
如何將多個名稱分配給 JS class 中的同一個 getter/setter function? 我知道我可以做這樣的事情:
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; }
}
但是有沒有一種簡單的方法可以在不復制代碼的情況下為相同的 function 提供多個名稱? 我知道我不需要不同的功能,但如果其他人正在使用 class(或者我只是忘記了)並且想為 function 使用不同的名稱(即不同的縮寫、灰色/灰色等),它會方便。
您可以簡單地返回另一個 function 的值:
static get anotherName() {
return this.name;
}
和
static set anotherName(value) {
this.name = value;
}
使用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'));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.