Mongoose传递类函数

Mongoose passing class functions

本文关键字:类函数 Mongoose      更新时间:2023-09-26

当我将函数传递给mongoose时,它似乎不再引用this。有更好的方法吗?由于长度原因,所有功能都被简化了。我无法编辑函数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);
    }
}

猫鼬是另一类:

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是如何使用的,但如果您需要用正确的this调用它,您可以尝试使用Function.prototype.bind方法:

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

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

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