Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中将对象方法作为参数传递_Javascript_Mongodb_Functional Programming_Prototypal Inheritance - Fatal编程技术网

在JavaScript中将对象方法作为参数传递

在JavaScript中将对象方法作为参数传递,javascript,mongodb,functional-programming,prototypal-inheritance,Javascript,Mongodb,Functional Programming,Prototypal Inheritance,我正在为Mongo集合编写JavaScript单元测试。我有一个集合数组,我想为这些集合生成一个项目计数数组。具体来说,我对使用Array.prototype.map感兴趣。我希望这样的事情能够奏效: const collections = [fooCollection, barCollection, bazCollection]; const counts = collections.map(Mongo.Collection.find).map(Mongo.Collection.Cursor.

我正在为Mongo集合编写JavaScript单元测试。我有一个集合数组,我想为这些集合生成一个项目计数数组。具体来说,我对使用
Array.prototype.map
感兴趣。我希望这样的事情能够奏效:

const collections = [fooCollection, barCollection, bazCollection];
const counts = collections.map(Mongo.Collection.find).map(Mongo.Collection.Cursor.count);

但是,我得到一个错误,告诉我,
Mongo.Collection.find
未定义。我认为这可能与
Mongo.Collection
是一个构造函数而不是一个实例化的对象有关,但我想更好地了解一下发生了什么。有人能解释一下为什么我的方法不起作用,以及我需要更改什么,以便将
find
方法传递给
map
?谢谢

find
count
是需要在集合实例上作为方法调用的原型函数(使用适当的
this
上下文)<代码>地图不会这样做

最好的解决方案是使用箭头函数:

const counts = collections.map(collection => collection.find()).map(cursor => cursor.count())
但也有一种方法可以让你不用:

const counts = collections
.map(Function.prototype.call, Mongo.Collection.prototype.find)
.map(Function.prototype.call, Mongo.Collection.Cursor.prototype.count);

那么
fooCollection
这就是
Mongo.Collection
实例?在第一次调用中,您试图
查找
什么?也许您实际上想要使用
Mongo.Collection.prototype.find
?啊哈。我也这么想并尝试过,但它仍然给了我一个未定义的错误。我再次尝试,并意识到
Mongo.Collection.prototype.find
确实有效。问题是
map
为每个元素调用
find(arrayItem)
,而不是
arrayItem.find()
。我可以通过一个匿名过程来做我想做的事情。这可能更好,因为这样我就可以从单个函数返回计数,而不是调用
map
两次。谢谢你的帮助。