Javascript,为什么在绑定节点回调中未定义“this”?

时间:2015-01-30 00:53:33

标签: javascript node.js

我第一次遇到这个错误而且我不知道会导致什么错误。

AccountController.create = function () {

  var password = this.param('password'),
      confirmPassword = this.param('confirmPassword'),
      account = new Account(),
      errorMessage = "",
      errors = "",
      error,
      errorCount;


  if (password !== confirmPassword) {
      this.req.flash('warning', 'passwords do not match');
      return this.redirect(this.urlFor({action: 'index'}));
  }

  account.email = this.param('email');
  account.set('password',  password);

  account.name.first = this.param('name.first');
  account.name.last = this.param('name.last');
  account.access = this.param('access');

  account.save(function (err, account, numberAffected) {
      if (err) {
          console.log("THIS: " + this);
          errorMessage = "";
          errors = err.errors;

          if (!errors) {
              errors = [{message: "There is already an account with this email address."}];
          }
          errorCount = errors.length;
          for (error = 0; error < errorCount; error = error + 1) {
              if (typeof errors[error] === "string") {
                  errorMessage += errors[error].message + " ";
              }
          }
          this.req.flash('warning', errorMessage);
          return this.redirect(this.urlFor({action: 'index'}));
      }

      return this.redirect(this.urlFor({controller: "profile",  action: 'login'}));

  }).bind(this);
};

我希望不需要额外的代码来使示例正常工作。

控制台输出(通过nodemon运行)如下所示:

THIS: undefined

/Users/crispensmith/Documents/cinchedStore/Site/app/controllers/account_controller.js:68
        this.req.flash('warning', errorMessage);
            ^
TypeError: Cannot read property 'req' of undefined

1 个答案:

答案 0 :(得分:2)

您正在对.bind(this)的返回值进行account.save,而不是您传入的函数。只需移动括号内的绑定;

account.save((function // ... possibly also use an extra parenthesis
    // ...
}).bind(this)); // to make the bind target more obvious?