问题
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?
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'
});
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?
Cheers
EDIT:
I need to be able to access varA
in more than one function, so it needs to be declared before the $(function() {});
回答1:
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.
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();
});
回答2:
As @mc10 mentioned this is primarily happening due to the race condition for accessing varA
. This is happening because $(document).ready()
waits for the readystatechange
event to fire as being ready before callback gets called, however it also runs setTimeOut
to check if the readystatechange
event has already fired.
Thus any code like :
$(document).ready(function(){
a();
$(b);
c();
});
Will execute in order
a
c
b
回答3:
By default, javascript variable get 'undefined' as the value untill they have been assigned some value. in this case your inner function is not getting execute first and out alert gets execute first and at that time value of the variable is 'undefined' so you gets the same.
to avoid this you may try as below.
$(document).ready(function () {
var varA;
(function () {
varA = 'varA has been altered!';
console.log(varA); //displays 'varA has been altered!'
}());
console.log(varA); //displays 'varA has been altered!'
});
来源:https://stackoverflow.com/questions/39545357/unable-to-update-global-variable-inside-a-function-and-call-it-outside-it-jquer