【问题标题】:coffeeescript: how to declare private function that can be used from within Array.reduce?coffeeescript:如何声明可以在 Array.reduce 中使用的私有函数?
【发布时间】:2015-12-10 10:20:07
【问题描述】:

主要目标是通过任何给定属性过滤数组中的重复项。我尝试使用的解决方案是在js中@https://stackoverflow.com/a/31194441/618220

我尝试在咖啡脚本中实现它。一切都很好,除了功能的范围。我不希望从外部调用 _indexOfProperty 函数 - 因为它在所有其他上下文中都没用。但是如果我将它 private (通过在声明中删除 @),我不能从 inputArray.reduce

中调用它

我的咖啡代码如下所示:

Utils = ->
    @filterItemsByProperty= (inputArray,property)=>
        if not _.isArray inputArray
            return inputArray
        r = inputArray.reduce(((a,b,c,d,e)=>
                if @._indexOfProperty(a,b,property) < 0
                    a.push(b)
                a
            ),[])
        r

    @_indexOfProperty= (a,b,prop) ->
        i = 0
        while i< a.length
            if a[i][prop] == b[prop]
                return i
            i++
        -1

    return

window.utils = Utils

这是我从其他地方调用它的方式:

App.utils.filterItemsByProperty(personArray,"name")

现在,任何人都可以这样做:

App.utils._indexOfProperty(1,2,3)

如何修改咖啡来阻止这种情况?

【问题讨论】:

    标签: javascript arrays coffeescript scope hoisting


    【解决方案1】:

    能否请您删除“@”,这次在 filterItemsByProperty 范围内定义一个局部变量“indexOfProperty”并为其分配“_indexOfProperty”(这样您就可以在 reduce() 中使用“indexOfProperty”)?

    @filterItemsByProperty = (inputArray, property) ->
        indexOfProperty = _indexOfProperty
        if !_.isArray(inputArray)
          return inputArray
        r = inputArray.reduce(((a, b, c, d, e) ->
          if indexOfProperty(a, b, property) < 0
            a.push b
            a
          ), [])
        r
    

    【讨论】:

      【解决方案2】:

      只是不要将_indexOfProperty 放在this / @ 上,它不会被看到:

      Utils = ->
          _indexOfProperty = (a,b,prop) ->
              i = 0
              while i< a.length
                  if a[i][prop] == b[prop]
                      return i
                  i++
              -1
      
          @filterItemsByProperty= (inputArray,property)=>
              if not _.isArray inputArray
                  return inputArray
              r = inputArray.reduce(((a,b,c,d,e)=>
                      if _indexOfProperty(a,b,property) < 0
                          a.push(b)
                      a
                  ),[])
              r
      
          return
      
      window.utils = Utils
      

      【讨论】:

      • 谢谢,它成功了,我很惊讶。正如问题中已经提到的,我知道删除 @ 将使函数私有。但我无法弄清楚为什么我今天早些时候无法从 .reduce 中访问它?明天必须检查。
      • @MrClan 抱歉,我一定已经读过了。可能你的 reducer 函数中仍然有 @ 符号,或者你可能有错字:)
      猜你喜欢
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 2012-11-08
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      相关资源
      最近更新 更多