【问题标题】:Access object properties from prototype从原型访问对象属性
【发布时间】:2012-04-25 18:29:59
【问题描述】:

我有一个为 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();

【问题讨论】:

    标签: javascript object prototype


    【解决方案1】:

    你在原型方法中做对了,你的错误在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;
    })();
    

    【讨论】:

    • 事实上,它完成了这项工作。 :D
    【解决方案2】:

    使用另一个参考:

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

    【讨论】:

    • that 指的是解决方案中的全局对象。
    • 这似乎与其他对象有冲突。我有两个与此非常相似的类,但是当我从 findUsers 对 this.collection 执行 console.log 时,它会从另一个类返回集合。
    猜你喜欢
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    相关资源
    最近更新 更多