我对 JS 很陌生,我试图在函数中设置变量的值,但设置值后它是“未定义”的。我的代码如下:
(function (name, context, definition){ 'use strict' ...} ('FP2', this, function (){...})
var fp = new FP2();
fp.get(function(result, components) { for (var index in components){...};
var IP = 'nothing';
$.getJSON('http://gd.geobytes.com/GetCityDetails?callback=?', function(data) {
this.IP = JSON.stringify(data, null, 2);
alert(this.IP);
});
alert(IP);
});
我希望 IP 变量在函数内部和外部具有相同的值,但事实并非如此。内部警报显示预期值,但函数外部的警报显示“无”。 来自类似问题1 , 2 , 3 ,我没有使用 var 重新声明函数内部的局部变量,而是使用“this.”指向函数外部的 IP 变量,所以我不明白为什么它不能按预期工作?
最佳答案
无需使用this.IP
,当您在API调用中使用this
时,您指的是该API调用函数本身。只需使用 IP
就可以了。
API 调用之外的 alert(IP);
也不会返回结果。即使在 API 返回一些数据之前,也会立即调用此函数调用,因此它将打印出先前的值 undefined
。
(function (name, context, definition){ 'use strict' ...} ('FP2', this, function (){...})
var fp = new FP2();
fp.get(function(result, components) { for (var index in components){...};
var IP = undefined;
$.getJSON('http://gd.geobytes.com/GetCityDetails?callback=?', function(data) {
IP = JSON.stringify(data, null, 2);
alert(IP);
});
alert(IP); //This will return undefined
});
关于JavaScript(变量范围): variable does not get the value assigned to it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52244649/