gpt4 book ai didi

javascript - NodeJS 这个引用

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

我有以下代码

this.userInfo = 'bla';

request({
url: 'https://api.api.ai/v1/entities?v=20150910',
headers : {
Authorization: "Bearer " + process.env.APIAI_ACCESS_TOKEN
},
method: 'GET'
}, function (error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
console.log(this.userInfo);
}.bind(this));

当我尝试打印 this.userInfo 变量时,我得到 undefined,但我在 this 上执行了 bind()。有人可以向我解释一下发生了什么事吗?

最佳答案

在您的代码范围中,this 被其他函数覆盖,因此您设置的值不可用。
当您使用可在函数外部使用的 this 调用绑定(bind)时,它的值与您设置的值相同,请参阅下面更正的代码。

let self= this;
self.userInfo = 'bla';
request({
url: 'https://api.api.ai/v1/entities?v=20150910',
headers : {
Authorization: "Bearer " + process.env.APIAI_ACCESS_TOKEN
},
method: 'GET'
}, function (error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
//scope of 'this' in callback function are removed, so have set value to self variable
console.log(self.userInfo);
}.bind(this));

关于javascript - NodeJS 这个引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42326678/

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