首页 > 解决方案 > 什么函数返回另一个函数,其参数也声明为常量?

问题描述

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

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的函数,但是为什么声明了具有相同名称的常量以及它们如何对应于返回函数的参数?

标签: javascriptfunctionreduxclosuresreselect

解决方案


有人可以解释什么函数totalSelector返回吗?

几乎可以肯定不是作者想要返回的意思。:-)

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

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
}

所以箭头函数体中的subtotalandtax是参数,而不是常量。

作者可能打算这样做:

export const totalSelector = state => {
  const subtotal = subtotalSelector(state)
  const tax = taxSelector(state)
  return () => ({ total: subtotal() + tax() })
  //     ^^                      ^^      ^^
}

……虽然很难确定。它接受一个状态对象并返回一个函数,当调用该函数时,它将选择该调用的小计和税款并返回一个总计。请注意,它不接受任何参数,并通过 和调用创建的函数。subtotalSelector(state)taxSelector(state)

subtotalSelectortaxSelector有同样的问题。


推荐阅读