[英]Passing Object Method as Parameter in JavaScript
I'm writing JavaScript unit tests for Mongo collections. 我正在为Mongo集合编写JavaScript单元测试。 I have an array of collections and I would like to produce an array of the item counts for those collections.
我有一个集合数组,我想为这些集合生成一个项目计数数组。 Specifically, I'm interested in using
Array.prototype.map
. 具体来说,我对使用
Array.prototype.map
感兴趣。 I would expect something like this to work: 我希望这样的工作:
const collections = [fooCollection, barCollection, bazCollection];
const counts = collections.map(Mongo.Collection.find).map(Mongo.Collection.Cursor.count);
But instead, I get an error telling me that Mongo.Collection.find
is undefined. 但是,相反,我收到一条错误消息,告诉我
Mongo.Collection.find
未定义。 I think this might have something to do with Mongo.Collection
being a constructor rather than an instantiated object, but I would like to understand what's going on a little better. 我认为这可能与
Mongo.Collection
是构造函数而不是实例化对象有关,但是我想了解发生了什么。 Can someone explain why my approach doesn't work and what I need to change so that I can pass the find
method to map
? 有人可以解释为什么我的方法不起作用以及我需要更改什么以便我可以通过
find
方法进行map
吗? Thanks! 谢谢!
find
and count
are prototype functions that need to be invoked as methods (with the proper this
context) on the collection instance. find
和count
是原型函数,需要在集合实例上作为方法(使用适当的this
上下文)进行调用。 map
doesn't do that. map
不这样做。
The best solution would be to use arrow functions: 最好的解决方案是使用箭头功能:
const counts = collections.map(collection => collection.find()).map(cursor => cursor.count())
but there is also an ugly trick that lets you do without: 但还有一个丑陋的技巧 ,可让您避免:
const counts = collections
.map(Function.prototype.call, Mongo.Collection.prototype.find)
.map(Function.prototype.call, Mongo.Collection.Cursor.prototype.count);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.