简体   繁体   English

奇怪的JavaScript作用域行为

[英]Weird JavaScript scoping behavior

Latey I've got some trouble with some weird javascript behavior. Latey我在一些怪异的javascript行为上遇到了麻烦。 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". 第一个和第二个警报显示实际值1)“ de” 2)“ en”。 The third alert shows "de" but shouldn't it be "en"?! 第三个警报显示“ de”,但不应该是“ 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. load方法是异步的。 The third alert is executed before the callback you pass to load . 第三个alert在传递给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 . 另外,您可以查看jQuery延迟对象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. 请注意,如果你使用递延对象API,你需要改变你打电话load到一个呼叫jQuery.getjQuery.ajax ,因为.load返回的jQuery的一个实例,不履行承诺的接口。

No, it shouldn't. 不,不应该。 "load" doesn't wait info from your "someValidUrl" would be fetched. “加载”不等待,您的“ someValidUrl”中的信息将被提取。 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". 它称为“异步”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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