簡體   English   中英

如何獲取與變量名稱無關的JavaScript分解參數?

[英]How to grab JavaScript destructured parameters independent of variable name?

希望制定參數,但已定義默認值

在我尋求具有解構功能的自文檔代碼的同時,DRY希望這樣做...

async function shampoo({ lather = true, rinse = true, repeat  2 } = {}) {
  await api.dogWasherMachine(magicalArguments) // ???
  // don't want to have to do this:
  // api.dogWasherMachine({ lather, rinse, repeat })
  // currenty arguments is {} and actual input is defined
}

如何獲得已定義的這些神奇參數?

參數沒有定義默認輸入,但是我該怎么做呢?

不可能僅在參數中執行此操作-解構必然將每個屬性提取到一個獨立的命名變量中,而不會留下對原始對象的引用。 您必須使用另一條語句來執行此操作,例如:

async function shampoo(param = {}) {
  const defaultObj = {
    lather: true,
    rinse: true,
    repeat: 2
  };
  await api.dogWasherMachine({ ...defaultObj, ...param });
}

我使用解構分配來自我文檔化用作接口的可繼承類。 在構造上,我獲得了智能感知的所有好處,並且在調用API時,一切都保持良好且干燥。

class washable {
  constructor({ lather = true, rinse = true, repeat = 2 } = {}) {
    this.lather = lather
    this.rinse = rinse
    this.repeat = repeat
  }
}

class dog extends washable {
  async shampoo() {
     await api.dogWasherMachine(this)
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM