2

我有一个为 node.js 包装 mongodb 客户端的类。findUsers当我打电话时,下面的类this.collection是未定义的。

如何this.collection从原型访问?

谢谢!

班级:

var Users;

Users = (function () {

    function Users(db) {

        db.collection('users', function (err, collection) {
           this.collection = collection;
        });
    }

    Users.prototype.findUsers = function (callback) {

        this.collection.find({}, function (err, results) {

        });
    }

    return Users;

})();

用法:

//db holds the db object already created
var user = new Users(db);
user.findUsers();
4

2 回答 2

3

你在原型方法中做对了,你的错误在db.collection().

var Users = (function () {
    function Users(db) {
        var that = this; // create a reference to "this" object
        db.collection('users', function (err, collection) {
            that.collection = collection; // and use that
        });
    }
    Users.prototype.findUsers = function (callback) {
        this.collection.find({}, function (err, results) {

        });
    }
    return Users;
})();
于 2012-04-25T18:43:11.663 回答
-1

使用另一个参考:

Users = (function(){
    var that = this;

    function users(db)
    {
         db.collection('users', function(err, collection)
         {
              that.collection = collection;
         }
    }
})();
于 2012-04-25T18:31:41.583 回答