[英]Node.js access the value of variable from another function
How do i get the value of myObject.myname, myObject.myage from the function getval? 如何从函数getval获取myObject.myname,myObject.myage的值? It returns undefined when i console.log it.
它在我console.log时返回undefined。 Btw I'm using node js.
顺便说一下,我正在使用节点js。 Thanks.
谢谢。
var post = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log('Response: ' + data);
var myObject = JSON.parse(data);
console.log('----------------------------------------------');
console.log(myObject.myname);
console.log(myObject.myage);
console.log('----------------------------------------------');
});
});
function getVal() {
//some code here
console.log(myObject.myname);
console.log(myObject.myage);
}
myObject
outside the anonymous function you pass to request
( var myObject
) instead of inside it. request
( var myObject
)而不是在其中的匿名函数之外声明myObject
。 At present it is a local variable. getVal()
after the HTTP response has been received (otherwise it won't have been set yet). getVal()
(否则它尚未设置)。 At present you aren't calling it at all. There is a scope issue, can you try this instead? 存在范围问题,您可以尝试这样做吗?
var myObject = {};
var post = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log('Response: ' + data);
myObject = JSON.parse(data);
console.log('----------------------------------------------');
console.log(myObject.myname);
console.log(myObject.myage);
console.log('----------------------------------------------');
});
});
function getVal() {
//some code here
console.log(myObject.myname);
console.log(myObject.myage);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.