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

coffeeescript: how to declare private function that can be used from within Array.reduce?

本文关键字:reduce Array 函数 何声明 声明 coffeeescript      更新时间:2023-09-26

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

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

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

只是不要把_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

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