无法更新函数内部的全局变量并在函数外部调用它(jQuery) [英] Unable to update global variable inside a function and call it outside it (jQuery)

查看:71
本文介绍了无法更新函数内部的全局变量并在函数外部调用它(jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了有关此主题的其他问题,很多人说,如果我在函数外部(在全局范围内)声明变量 varA ,则它是全局函数,因此可以使用和更新任何功能,对吧?

I've read some other questions about this topic and many say that if I declare the variable varA outside my function (in de global scope), it is a global function, and so it is accessible for any function to use and update, right?

现在,我有一个示例,其中我在函数外部声明了一个变量,在函数内部对其进行了更改,但是当我在函数外部调用它时,它显示为 undefined ,如果我在在函数内部调用它,它就会被更改.

Now, I have this example where I declare a variable outside a function, alter it inside the function, but when I call it outside the function, it displays as undefined, where if I'm to call it inside the function, it is altered.

$(document).ready(function() {

    var varA;

    $(function() {

        varA = 'varA has been altered!';

        alert(varA); //displays 'varA has been altered!'

    });

    alert(varA); //displays 'undefined'
});

这对我来说似乎不合逻辑:当我更改全局变量时,第二个 alert(); 是否不应该显示 varA 的值?

This does not seem logical to me: when I alter a global variable, shouldn't the second alert(); display the value of varA?

此问题的解决方法是什么?如何更改函数内部的全局变量并在函数外部获取该值?

What is a workaround for this problem? How can I alter a global variable inside a function and get that value outside the function?

欢呼

我需要能够在多个函数中访问 varA ,因此需要在 $(function(){});

I need to be able to access varA in more than one function, so it needs to be declared before the $(function() {});

推荐答案

问题是访问 varA 存在竞争条件:如果 $(function(){}); 在函数内部的代码之前运行,然后将不会对其进行定义.

The issue is that there's a race condition for accessing varA: if the code below the $(function() {}); runs before the code inside the function, then it will not be defined.

在这种情况下, $(document).ready() $()相同,因此 document 应该已经在函数内部做好准备.因此,您可以运行

In this case, $(document).ready() is the same thing as $(), so the document should already be ready inside the function. Thus, you can just run

$(function() {
    var varA;

    varA = 'varA has been altered!';
    alert(varA); //displays 'varA has been altered!'
});

这不是作用域的问题:这是一个作用域相似的示例,但是竞争条件已删除,因此代码将起作用:

This isn't an issue with scoping: here's an example where the scoping is similar, but the race condition is removed, so the code will work:

$(function() {
    var varA;
    var def = $.Deferred();
    def.then(function() {
        varA = 'varA has been altered!';
    }).then(function() {
        alert(varA); //displays 'varA has been altered!'
    });

    def.resolve();
});

这篇关于无法更新函数内部的全局变量并在函数外部调用它(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆