javascript - 什么函数返回另一个函数,其参数也声明为常量?
问题描述
我完全迷路了。以下是考虑重新选择库的文章中的简短代码:
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返回的函数吗?
我看到它返回另一个带有参数subtotal和tax的函数,但是为什么声明了具有相同名称的常量以及它们如何对应于返回函数的参数?
解决方案
有人可以解释什么函数
totalSelector
返回吗?
几乎可以肯定不是作者想要返回的意思。:-)
它返回的是一个函数,当使用两个参数调用时,它返回一个对象,该对象的total
属性是传入的两个参数的总和。该行totalSelector
之前return
的所有内容都完全没有意义并且被忽略了,因为作者已经隐藏了subtotal
andtax
常量它返回的箭头函数中的参数:
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
}
所以箭头函数体中的subtotal
andtax
是参数,而不是常量。
作者可能打算这样做:
export const totalSelector = state => {
const subtotal = subtotalSelector(state)
const tax = taxSelector(state)
return () => ({ total: subtotal() + tax() })
// ^^ ^^ ^^
}
……虽然很难确定。它接受一个状态对象并返回一个函数,当调用该函数时,它将选择该调用的小计和税款并返回一个总计。请注意,它不接受任何参数,并通过 和调用它创建的函数。subtotalSelector(state)
taxSelector(state)
subtotalSelector
并taxSelector
有同样的问题。
推荐阅读
- javascript - 替换字符串中的字母 - 为什么函数不起作用?
- php - 查询需要很长时间
- powershell - 如何让我的函数运行计算机名称的自定义对象?
- reactjs - 如何在 reactjs 中映射图像
- javascript - 多维 PHP 数组转换为 Javascript 数组
- java - ArrayList 一直给我 null
- node.js - 如何在 Node.js 中监听 MongoDB 的变化?
- c# - 当提交时选中不同的单选按钮时,返回视图时不会记住该复选框
- sql - 将多个 oracle 连接转换为多个 ANSI 连接
- c++ - 为什么我得到“未定义的引用”到我_知道_已定义的静态数据成员