【问题标题】:JavaScript scoping issue with Mongoose and Node.jsMongoose 和 Node.js 的 JavaScript 范围问题
【发布时间】:2014-03-29 07:04:18
【问题描述】:

我在这里使用 Node,下面的函数被用作控制器动作。我正在使用 Mongoose 访问模型,并且在 Game.findById() 的范围内,我无法访问它上面的任何变量,即 this.player 和 this.gameId。

有谁知道我做错了什么?请注意,我想访问 console.log() 语句所在的变量,但我无法访问它。 this.player 返回未定义。提前感谢您的帮助。

exports.cleanup = function(req, res) {
  this.player = req.body;
  this.gameId = req.url.split('/')[2];
  debugger;
  Game.findById(this.gameId, function(err, game) {
    if (err) return err;
    console.log(this.player);
  });
}; 

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    this 指的是两个函数内部的不同事物,每个函数都有自己的作用域和自己的this(尽管this 在某些情况下可能未定义,请参阅下面的一些参考资料)。

    您需要的是类似于以下内容 - 请注意 self 变量。

    exports.cleanup = function(req, res) {
      this.player = req.body;
      this.gameId = req.url.split('/')[2];
      var self=this;
      debugger;
      Game.findById(this.gameId, function(err, game) {
        if (err) return err;
        console.log(self.player);
      });
    }; 
    

    一些可能有助于理解this的资源:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      相关资源
      最近更新 更多