coffeeescript:如何声明可以在Array.reduce中使用的私有函数?

时间:2015-09-14 12:06:56

标签: javascript arrays coffeescript scope hoisting

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

我试图在coffeescript中实现它。除了函数的范围外,这一切都很好。我不希望从外部调用 _indexOfProperty 函数 - 因为它在所有其他上下文中都是无用的。但是,如果我将其设为私人(通过删除声明中的@),我无法在 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)

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

请你删除'@',这次在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