JavaScript (node.js) 变量在内部函数调用时无法访问。 now.js
我在节点项目中使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将代码更改为:
在您的内部函数中,
this
可能被设置为其他内容。因此,为了保留您想要访问的值,您可以将其分配给内部函数中可用的不同局部变量。Change the code to this:
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.使用
Function.prototype.bind
将this
的值设置为你想要的值Use
Function.prototype.bind
to set the value ofthis
to the value you want