猫鼬传递 class 函数

Mongoose passing class functions

当我将函数传递给 mongoose 时,它​​似乎不再引用 this。有没有更好的方法来解决这个问题?由于篇幅原因,所有功能都进行了简化。我无法编辑函数 getUsernameForId 以获取其他参数。

我有 class:

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 是另一个 class 这样的:

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

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

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