繁体   English   中英

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

[英]Passing Object Method as Parameter in JavaScript

我正在为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吗? 谢谢!

findcount是原型函数,需要在集合实例上作为方法(使用适当的this上下文)进行调用。 map不这样做。

最好的解决方案是使用箭头功能:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM