JavaScript (node.js) 变量在内部函数调用时无法访问。 now.js

发布于 2024-11-26 01:25:48 字数 376 浏览 0 评论 0原文

我在节点项目中使用 now.js 和 Mongoose,并且在访问 mongoose 函数内的 this.now 对象时遇到问题。例如

everyone.now.joinDoc = function (project_id){  
  this.now.talk(); //this will work
  Project.findOne({'_id':project_id}, function(err, project){
    if(project){
      this.now.talk(); // this will not work "TypeError: Cannot call method 'bark' of undefined"
    };
  });
};

I am using now.js and Mongoose in a node project and am having trouble accessing the this.now object inside of a mongoose function. E.g.

everyone.now.joinDoc = function (project_id){  
  this.now.talk(); //this will work
  Project.findOne({'_id':project_id}, function(err, project){
    if(project){
      this.now.talk(); // this will not work "TypeError: Cannot call method 'bark' of undefined"
    };
  });
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

李白 2024-12-03 01:25:48

将代码更改为:

everyone.now.joinDoc = function (project_id){  
  this.now.talk();  // this will work
  var that = this;  // save 'this' to something else so it will be available when 'this' has been changed
  Project.findOne({'_id':project_id}, function(err, project){
    if(project){
      that.now.talk();  // use local variable 'that' which hasn't been changed
    };
  });
};

在您的内部函数中,this 可能被设置为其他内容。因此,为了保留您想要访问的值,您可以将其分配给内部函数中可用的不同局部变量。

Change the code to this:

everyone.now.joinDoc = function (project_id){  
  this.now.talk();  // this will work
  var that = this;  // save 'this' to something else so it will be available when 'this' has been changed
  Project.findOne({'_id':project_id}, function(err, project){
    if(project){
      that.now.talk();  // use local variable 'that' which hasn't been changed
    };
  });
};

Inside your inner function, the this is probably being set to something else. So, to preserve the value you want to access, you assign it to a different local variable that will be available in the inner function.

〃温暖了心ぐ 2024-12-03 01:25:48
everyone.now.joinDoc = function (project_id){  
  this.now.talk();  // this will work
  Project.findOne({'_id':project_id}, (function(tunnel, err, project){
    if(project){
      this.now.talk(); 
    };
  }).bind(this, "tunnel")); // overwrite `this` in callback to refer to correct `this`
};

使用Function.prototype.bindthis的值设置为你想要的值

everyone.now.joinDoc = function (project_id){  
  this.now.talk();  // this will work
  Project.findOne({'_id':project_id}, (function(tunnel, err, project){
    if(project){
      this.now.talk(); 
    };
  }).bind(this, "tunnel")); // overwrite `this` in callback to refer to correct `this`
};

Use Function.prototype.bind to set the value of this to the value you want

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文