简体   繁体   English

Node.js从另一个函数访问变量的值

[英]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);
    }
  1. Declare myObject outside the anonymous function you pass to request ( var myObject ) instead of inside it. 您传递给requestvar myObject )而不是在其中的匿名函数之外声明myObject At present it is a local variable. 目前它是一个局部变量。
  2. Call getVal() after the HTTP response has been received (otherwise it won't have been set yet). 收到HTTP响应调用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM