【发布时间】:2015-09-21 02:52:48
【问题描述】:
我刚刚注意到如果我的类中有一个方法,如果我在 async.auto 中调用它们,我将无法在我的其他原型中使用 this 关键字访问它,或者...请参阅示例代码以获得更多说明和我的解决方法.
你会这样做吗?换句话说,这是 Node.JS 中最优雅的方式吗?
function foo(config) {
var self = Object.create(foo.prototype)
self.db = nano.db.use(config.db.dbName);
return self
}
foo.prototype.method1 = function () {
// The workaround to use this.db is to store this.db in a variable, is this elegant?!? Would you do the same?
var db = this.db;
async.auto({
check_DB: function (next) {
// do some operations here
next();
},
insert_DB: ['check_DB', function (callback, results) {
// Note1: interestingly this.db is not going to work! in other words here this.db is undefined
db.insert(value, function (err, body) {
//Do some other operations here
})
}]
});
}
foo.prototype.method2 = function () {
// The workaround to use this.db is to store this.db in a variable?!? Would you do the same?
var db = this.db;
db.get("baz", function (err, body) {
// Do some operatiuons
// Note2: interestingly this.db is not going to work here either!
db.get("bar", function (err, response) {
// do some other operations
})
}
});
}
【问题讨论】:
标签: javascript node.js oop