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

标签 javascript function redux closures reselect

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

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

最佳答案

Can someone explain what function totalSelector returns?

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

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

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
}

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

作者大概是有这个意思的:

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

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

subtotalSelectortaxSelector 有同样的问题。

关于javascript - 什么函数返回另一个参数也声明为常量的函数呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52291703/

相关文章:

c - 如何使用在 Modelica 中调用的两个 C 函数之间使用的全局变量?

javascript - 不更改 url 的单页 Web 应用程序

javascript - JS : What do the curly braces inside function parameter declarations mean?

javascript - 为什么我的 JS 代码只运行一次?

javascript - 使用 highchart 来自 MySQL 的实时数据

javascript - Angular Highcharts - 单击后图表引用消失

javascript - 是否有替代 JavaScript 的方法来编写客户端 Web 应用程序代码?

javascript - 如何从主函数外部调用函数?

function - 在 Excel 中设置范围时 VBA 失败

reactjs - 将 mapDispatchToProps 定义为对象