简体   繁体   English

Mongoose和Node.js的JavaScript作用域问题

[英]JavaScript scoping issue with Mongoose and Node.js

I'm using Node here and the following function is being used as a controller action. 我在这里使用Node,并且以下功能被用作控制器动作。 I'm using Mongoose to access a model and within the scope of the Game.findById(), I cannot access any of the variables above it, namely this.player and this.gameId. 我正在使用猫鼬访问模型,并且在Game.findById()的范围内,我无法访问模型上方的任何变量,即this.player和this.gameId。

Does anyone know what I doing wrong? 有人知道我做错了吗? Note that I want to access the variables where the console.log() statement is, but I can't access it. 请注意,我想访问console.log()语句所在的变量,但无法访问它。 this.player returns undefined. this.player返回未定义。 Thanks in advance for your help. 在此先感谢您的帮助。

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);
  });
}; 

this is referring to different things inside the two functions, each of which has its own scope and its own this (although this might be undefined in some circumstances, see a couple of references below). this指的是不同的东西两个函数里面,每一个都有自己的范围,自己的this (虽然this可能会在某些情况下是不确定的,看到一对夫妇的参考下图)。

What you'll want is something like the following - note the self variable. 您将需要以下内容-注意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);
  });
}; 

A couple of resources which may be of help understanding this : 一些资源可能有助于理解this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM