【发布时间】:2023-04-06 05:30:01
【问题描述】:
我对 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 变量,所以我不明白为什么它不能按预期工作?
【问题讨论】:
标签: javascript scope global-variables