简体   繁体   中英

Weird JavaScript scoping behavior

Latey I've got some trouble with some weird javascript behavior. I want to do something like this:

var lang = null;

function getLang() {
    if (browserLanguageIsGerman) {
        lang = 'de';
    }
    else {
        lang = 'en';
    }
    // alert(lang) shows "de"

    $('#someID').load(someValidUrl, null, 
        function(response, status, xhr) {
            if(languageSettingsOnFacebookIsGerman) {
                lang = 'de';
            }
            else {
                lang = 'en';
            }
            // alert(lang) show "en"
    );
    // alert(lang) shows "de"
}

The first and the second alerts show the expacted value 1) "de" 2) "en". The third alert shows "de" but shouldn't it be "en"?! Also the second alert pops up after the third alert.

Can someone please obvious bug in my mind? :)

Thanks in advance!

This is not an issue with scope. The load method is asynchronous. The third alert is executed before the callback you pass to load . Move any code that depends on the result of that async call into the callback.

Alternatively, you can look into the jQuery deferred objects API . Note that if you were to use the deferred object API you would need to change you call to load to a call to jQuery.get or jQuery.ajax , since .load returns an instance of jQuery, which doesn't implement the Promise interface.

No, it shouldn't. "load" doesn't wait info from your "someValidUrl" would be fetched. Instead, it postpones your internal function to be executed later, when the info would be available, and immediately returns without waiting. It is called "asyncronous".

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