问题:我想在函数内将变量设为全局变量
这有效:
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成为全局变量?预先感谢
答案 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);
}