使用闭包来存储和检索数据

时间:2016-11-26 18:12:28

标签: javascript jquery closures

我正在尝试使用闭包来同时存储和检索变量。

我正在使用JSONP并回调函数

http://freegeoip.net/json/?callback=geoIPInfo

封闭

function geoIPInfo(newGeoData) {
    var geoInfo;
    if (newGeoData) {
        geoInfo = newGeoData;
    }
    var provideGeoData = function () {
        return geoInfo;
    };

    return provideGeoData();
}

我首先想要存储数据,然后使用像

这样的简单调用从闭包中检索最后保存的数据
geoIPInfo()

如果参数提供它将设置新信息,否则它将返回现有信息。

但在我的情况下,数据已成功设置,但当我尝试获取设置数据时,我得到undefined

 $("#super_button").click(function (e) {
            alert(geoIPInfo());
            e.preventDefault();
        });

我的闭包理解有什么问题? 请解释。

谢谢。

2 个答案:

答案 0 :(得分:2)

This will work. The idea here is we create a function that returns a function with that accepts a parameter and we store geoInfo in a closure to keep it value. Idk if that makes sense, if you need a better explanation I can give it another try :)

var geoIPInfo  = function() {
    var geoInfo;
    var provideGeoData = function (newGeoData) {
        if (newGeoData) {
            geoInfo = newGeoData;
        }
        return geoInfo;
    };
    return provideGeoData;
}();

答案 1 :(得分:1)

每次致电geoIPInfo()时,您都会重新声明本地变量geoInfo。您只需要声明geoInfo一次,并通过关闭可以访问geoIPInfo()



//Create a closure
var geoIPInfo = (function(){ 

  //Private variable, available via closure
  var geoInfo;

  function geoIPInfo(newGeoData) {
   
    if (newGeoData) {
      geoInfo = newGeoData;
    }
 
    var provideGeoData = function () {
      return geoInfo;
    };

    return provideGeoData();
  }

  return geoIPInfo;
})();

alert(geoIPInfo()); //undefined
geoIPInfo('Some Data');
alert(geoIPInfo()); //'Some Data'




在这里,我们使用Immediately-Invoked Function Expression (IIFE)创建了一个闭包。