繁体   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