gzbuaapzroyn gzbuaapzroyn - 7 days ago 6
Javascript Question

Using closure for storing and retrieving data

I am trying to use closure for storing and retrieving variable at the same time.

I am using

JSONP
and callback to the function

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


Closure

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

return provideGeoData();
}


I want firstly to store data and than retrieve last saved data from the closure using simple call like that

geoIPInfo()


If argument provided it will set new info otherwise it will return existing one.

But in my case data is set successfully, but when I try to get set data I get
undefined


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


What is wrong with my closure understanding ?
Please explain.

Thank you.

Answer

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;
}();
Comments