mongoose传递类function

当我把函数传给mongoose时,似乎不再有这个参考。 有没有更好的方法去做这件事? 所有function都因为长度原因而被简化。 我无法编辑getUsernameForId函数来获取其他参数。

我有课:

 var class = new function() { this.func1 = function(data) { return data + "test"; } this.func2 = function(data) { var next = function(username) { return this.func1(username); // THIS THROWS undefined is not a function } mongoose.getUsernameForId(1, func3); } } 

mongoose是这样的另一个类:

 var getUsernameForId = function(id, callback) { user_model.findOne({"id": id}, function(err, user) { if(err) { throw err; } callback(user.username); }); } 

如何解决undefined is not a function error 。 我不想复制代码,因为func1在现实中很长。

从代码中不清楚next是如何使用的,但是如果需要使用正确的方法调用它,可以尝试使用Function.prototype.bind方法:

 this.func2 = function(data) { var next = function(username) { return this.func1(username); }.bind(this); mongoose.getUsernameForId(1, func3); } 

我假设你简化了post的代码, next在现实中做了更多的事情。 但是,如果它确实只是返回this.func1结果,那么你可以缩短它:

 var next = this.func1.bind(this);