这个问题在这里已有答案:
问题:我想在函数内部创建一个变量作为全局变量
这有效:
var x;
function myFunction() {
x = 999;
}
myFunction();
console.log(x);
但是这个在尝试从API Result声明一个全局变量时不起作用
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作为全局变量?提前致谢
这是因为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);
}