【问题标题】:accessing method of the class inside of async module or访问异步模块内部类的方法或
【发布时间】: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


    【解决方案1】:

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

    与方法 2 中的 db.get(... 相同。它也以完全相同的方式更改“this”的范围。

    因此,在调用要从外部范围访问“this”的函数以将“this”分配给其他变量之前,在 javascript 代码中这是很正常的,就像您所做的那样:

       var db = this.db;
    

    很多人会将它分配给类似的东西:“self”、“_this”、“that”等。

    【讨论】:

    • 感谢您的确认!第二种情况也是预期的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多