主要目标是通过任何给定属性过滤数组中的重复项。我尝试使用的解决方案是在 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/