Javascript在带有参数的函数内声明全局变量

时间:2019-04-06 05:54:54

标签: javascript function api callback global-variables

问题:我想在函数内将变量设为全局变量

这有效:

var x;
function myFunction() {
    x = 999;
}
myFunction();
console.log(x);

但是在尝试从API结果声明全局变量时,此方法不起作用

webOS.service.request(url, {
    onSuccess: function (data) {
        var serial = data.idList[0].idValue;
        var udid = serial; // This is the variable that I want
        callback(udid); // Trying to get this udid out of this API call
},
});

var sn;
function callback(udid) {
    sn = udid; // I want this as my global variable
}
callback(udid); // produces an error which says udid not defined
console.log(sn); // undefined

如何使var sn成为全局变量?预先感谢

1 个答案:

答案 0 :(得分:0)

这是因为udid不在您正在调用callback的范围内定义-您正在callback函数中调用onSuccess,所以您没有需要再次调用它。您还需要将console.log放在callback函数中:

webOS.service.request(url, {
    onSuccess: function (data) {
        var serial = data.idList[0].idValue;
        var udid = serial; // This is the variable that I want
        callback(udid); // Trying to get this udid out of this API call
    },
});
var sn;
function callback(udid) {
    sn = udid; // I want this as my global variable
    console.log(sn);
}