在回调中重用变量/对象

时间:2012-04-10 17:56:17

标签: javascript node.js callback

我想知道这一点,在下面的例子中,处理重用helpers对象的最佳方法是什么?

var test = {
  Projects: 'an object goes here',
  helpers: require('../helpers'),

  test: function(req, res) {
    if (this.helpers.is_post(req)) {
      // tried this
      var test = this.helpers;

      this.Projects.byCode(req.params.project_code, function(project) {
        if (!project) {
          this.helpers.flash(req, 'error', 'Unable to find project.');
          // tried this
          helpers.flash(req, 'error', 'Unable to find project.');
          res.redirect('/projects');
        }
      });
    }
  }
};

我知道我不能在回调中重复使用变量,对象等,因为它们不是在同一个运行时执行的,但是仍然必须有某种更好/更清晰的方法来做这样的事情?

即使我试图将this.helpers重新分配给另一个变量,它也会给我一些错误,说明它是未定义的。

谢谢!

1 个答案:

答案 0 :(得分:4)

为什么你认为你不能在回调中重用变量?它们不仅在同一个运行时执行,而且在同一个线程中执行!这就是JavaScript的魅力。

相反,您的问题很可能是滥用此问题。例如,如果没有分配给var test = this.helpers,它肯定不会起作用。如果你像这样调用方法,那么即使这样也行不通:

var testIt = test.test;
testIt(req, res);

请尝试以下内容:

var helpers = require('../helpers');

var test = {
  Projects: 'an object goes here',

  test: function(req, res) {
    if (helpers.is_post(req)) {
      this.Projects.byCode(req.params.project_code, function(project) {
        if (!project) {
          helpers.flash(req, 'error', 'Unable to find project.');
          res.redirect('/projects');
        }
      });
    }
  }
};

无论如何,将整个模块作为对象的属性是非常荒谬的。