访问异步模块或类中的类的方法

时间:2015-09-21 02:52:49

标签: javascript node.js oop

我刚刚注意到,如果我在我的其他原型中使用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 }) } }); } 关键字在我的班级中有一个方法,如果我在async.auto中调用它们或者...请参阅示例代码以获得更多说明我的解决方法。

你会这样做吗?换句话说,这是Node.JS中最优雅的方式吗?

x;y;z 
[1]  4  6  4  6 17 10 13 27 33 19
[1]  3  2  5 13 22 20 23 19 31 14
[1] 21  6 12 35 19 44 34 23 26 33

1 个答案:

答案 0 :(得分:0)

这是完全正确的。 async.auto(...函数将改变"这个"的范围。它不是特定的异步,而是调用另一个中的javascript函数。

同样处理db.get(...在方法2中。它也以完全相同的方式改变"这个"的范围。

所以在调用你想要访问的函数之前,javascript代码是很正常的,这个"从外部范围分配"这个"正如你已经完成的那样,对其他一些变量:

   var db = this.db;

许多人会将此分配给:" self'," _this",""等