代码之家  ›  专栏  ›  技术社区  ›  Andrej KirejeÅ­

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

  •  1
  • Andrej KirejeÅ­  · 技术社区  · 6 年前

    我完全迷路了。下面是一个简短的代码 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 })
    }
    

    总选择器 退货?

    我看到它返回另一个带参数的函数

    2 回复  |  直到 6 年前
        1
  •  2
  •   T.J. Crowder    6 年前

    有人能解释一下什么功能吗 totalSelector

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

    total 属性,它是传入的两个参数之和。里面的一切 总选择器 之前 这个 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
    }
    

    所以 小计 在arrow函数的主体中是参数,而不是常量。

    作者可能打算这样做:

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

    从那个电话开始 返回一个总数。请注意,它不接受任何参数,并且 subtotalSelector(state) taxSelector(state) .

    subtotalSelector taxSelector 有同样的问题。

        2
  •  0
  •   filip    6 年前

    totalSelector() subtotal tax .

    returned function object with the property total 这是通过 subtotal + tax

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

    推荐文章