gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:59:51 24 4
gpt4 key购买 nike

我在 Node 项目中使用 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"
};
});
};

最佳答案

将代码更改为:

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 可能被设置为其他内容。因此,为了保留您想要访问的值,您可以将其分配给内部函数中可用的不同局部变量。

关于JavaScript (node.js) 变量在内部函数调用时无法访问。 now.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6801569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com