Javascript 什么函数返回另一个参数也声明为常量的函数?

Javascript 什么函数返回另一个参数也声明为常量的函数?,javascript,function,redux,closures,reselect,Javascript,Function,Redux,Closures,Reselect,我完全迷路了。以下是考虑重新选择库中的简短代码: const shopItemsSelector = state => state.shop.items const taxPercentSelector = state => state.shop.taxPercent const subtotalSelector = state => { const items = shopItems(state) return items => items.reduce((a

我完全迷路了。以下是考虑重新选择库中的简短代码:

const shopItemsSelector = state => state.shop.items
const taxPercentSelector = state => state.shop.taxPercent

const subtotalSelector = state => {
  const items = shopItems(state)
  return items => items.reduce((acc, item) => acc + item.value, 0)
}

const taxSelector = state => {
  const subtotal = subtotalSelector(state)
  const taxPercent = taxPercentSelector(state)
  return (subtotal, taxPercent) => subtotal * (taxPercent / 100)
}

export const totalSelector = state => {
  const subtotal = subtotalSelector(state)
  const tax = taxSelector(state)
  return (subtotal, tax) => ({ total: subtotal + tax })
}
有人能解释一下totalSelector返回什么函数吗

我看到它返回另一个函数,其中包含参数subtotaltax,但为什么会有声明名称相同的常量,以及它们如何对应于返回函数的参数

有人能解释一下
totalSelector
返回什么函数吗

几乎可以肯定的是,这并不是作者的本意。:-)

它返回的是一个函数,当使用两个参数调用时,该函数返回一个对象,该对象的
total
属性是传入的两个参数之和。
返回
行之前的
totalSelector
中的所有内容都完全没有意义且被忽略,因为作者使用返回的箭头函数中的参数隐藏了
小计
税务
常量:

export const totalSelector = state => {
  const subtotal = subtotalSelector(state) // <=== These
  const tax = taxSelector(state)           // <=== constants
  //      vvvvvvvvvvvvv------------ are shadowed by these parameter declarations
  return (subtotal, tax) => ({ total: subtotal + tax })
  //                                  ^^^^^^^^^^^^^^ -- so this uses the parameters
}
…虽然很难确定。它接受一个状态对象并返回一个函数,该函数在调用时将选择该调用的小计和税并返回总计。请注意,它不接受任何参数,并调用通过
subtotalSelector(state)
taxSelector(state)
创建的函数

subtotalSelector
taxSelector
有相同的问题。

totalSelector()
返回一个函数,该函数需要两个参数
subtotal
tax

返回函数
返回一个属性为total的
对象,该属性通过
小计+税

声明的常量与返回的函数无关


请解释downvote:)

如果totalSelector返回的函数没有任何参数,它将使用这两个常量创建一个闭包,但在这里它们什么都不做不是你感到困惑的。:-)我没有投反对票。但我猜问题的作者和选择器中的const声明混淆了,所以您在测试中跳过了这一部分explanation@Andrey我明白你的意思。发布后2分钟进行编辑。但谢谢你的解释:)
export const totalSelector = state => {
  const subtotal = subtotalSelector(state)
  const tax = taxSelector(state)
  return () => ({ total: subtotal() + tax() })
  //     ^^                      ^^      ^^
}