我完全迷路了。以下是来自 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 返回的是什么函数?
我看到它返回另一个带有参数subtotal 和tax 的函数,但是为什么声明了同名常量以及它们如何对应于返回函数的参数?
最佳答案
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
}
所以箭头函数体中的subtotal
和tax
是参数,不是常量。
作者大概是有这个意思的:
export const totalSelector = state => {
const subtotal = subtotalSelector(state)
const tax = taxSelector(state)
return () => ({ total: subtotal() + tax() })
// ^^ ^^ ^^
}
...虽然很难确定。它接受一个状态对象并返回一个函数,该函数在被调用时将选择小计和征税调用并返回总计。请注意,它不接受任何参数,并且调用它通过 subtotalSelector(state)
和 taxSelector(state)
创建的函数。
subtotalSelector
和taxSelector
有同样的问题。
关于javascript - 什么函数返回另一个参数也声明为常量的函数呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52291703/