简体   繁体   中英

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.

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

Each time you call geoIPInfo() , you're re-declaring the local variable geoInfo . You'll want to declare geoInfo once, and have it accessible to geoIPInfo() via a closure:

 //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' 

Here, we're creating a closure using an Immediately-Invoked Function Expression (IIFE) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM