javascript - Coffeeescript : how to declare private function that can be used from within Array. 减少?

标签 javascript arrays coffeescript scope hoisting

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

我尝试在coffeescript中实现它。除了功能范围之外,一切都很好。我不希望从外部调用 _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)

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

最佳答案

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

关于javascript - Coffeeescript : how to declare private function that can be used from within Array. 减少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32564392/

相关文章:

coffeescript - 如何在 Atom 中获取事件文件的名称?

javascript - 如何根据用户的点击次数排序链接的顺序并使用JavaScript将其保存到本地存储?

javascript - 尝试使用 Google Assistant 应用连接到服务器

javascript - 编辑和删除 angularjs 中的表格行

ruby-on-rails - 对具有波兰语字符的字符串数组进行排序

javascript 函数链接,链成员无需相互了解

javascript - 无法使用 Passport.js 和 Express 4 访问 req.user

Ruby - 如何提高数组扫描的性能?

c++ - 如何制作包含数组的 vector ?

ruby-on-rails - 检查窗口后执行脚本