簡體   English   中英

在組合中使用Object.assign()時,可以使用相同的函數名稱嗎?

[英]Can I use the same function names when using Object.assign() in composition?

上下文

我使用Javascript中的合成范例創建了一個新對象。

const canUpdateScore = (state) => ({
    update: (spell) => state.score-- 
})

const mage = (name) => {
  let state = {
    score: 100,
  }
  return Object.assign(state, canUpdateScore(state));
}

scorcher = mage()
scorcher.update();    // call the update method
console.log(scorcher.score)    // 99

將輔助方法命名為與返回該方法的外部函數相同(在下面的示例中)會引起混淆嗎?還是最好使用其他名稱(在上面的上下文中)?

const updateScore = (state) => ({
    updateScore: (spell) => state.score-- 
})

const mage = (name) => {
  let state = {
    score: 100,
  }
  return Object.assign(state, updateScore(state));
}

scorcher = mage()
scorcher.updateScore();    // call the update method
console.log(scorcher.score)    // 99

使用合成的慣例是“做事者”。 您的updateScore撰寫者是“ scoreUpdater”,而它是“ updateScore”。

將這樣寫出來:

const scoreUpdater = (state) => ({
    updateScore: (spell) => state.score-- 
})

現在,出於清楚起見和設計方面的原因,對其本身進行update是很糟糕的。 想象一下,您會發現另一個將更新運行狀況的組件的情況:healthUpdater也將實現update方法。 其中一個將覆蓋另一個。

通常,組合物的屬性名稱應以某種方式明確引用組合物本身。

canUpdateScore絕對是對象的較差名稱,無論它暗示的是布爾值,事實並非如此。

暫無
暫無

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

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