>问题:我想将函数中的变量作为全局变量
这有效:
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 作为全局变量?提前致谢
这是因为udid
没有在你调用callback
的作用域中定义 - 你在onSuccess
函数中调用callback
,所以你不需要再次调用它。您还需要将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);
}