问题
Usually, defining a variable outside functions is enough to let it be "global". In my case, however, situation seems to be different.
var username = null;
function myFunction_1() {
username="pippo";
myobject.myfunction(function (data){ username="mickey" })
console.log("1: ", username);
}
myFunction_1();
I expected this code to log "1: mickey". However, if i set the variable inside a callback function logs "1: pippo", that is setting inside the callback gets ignored. What i'm missing? Setting variable in this way is not enough?
回答1:
Your code is being executed from the top of the page as following :username
gets declared and set to = null
-> myFunction_1()
get's defined -> myFunction_1()
gets called -> username
gets set to 'pippo'
-> console.logs
"1: pippo"
-> console.logs
"2: pippo"
-> myFunction_2()
get's defined -> myFunction_2()
gets called -> console.logs
"3: pippo"
this happens in this sequence assuming that this code runs, which it does not in your case.
Assuming that salvaUsername()
looks like function salvaUsername(){ return username; }
username is null as it have never reached the point of assignment that happens in myFunction_1()
. (It's actually surprising that output is not undefined
but null
).
UPDATE
In this case myFunction_1()
never runs so username
doesn't get set to 'pippo'
hence the outcome.
回答2:
Assuming that code is not inside a function you haven't shown, username
is a global variable. If you look at the value of username
before calling myFunction_1
, it will be null
. If you call myFunction_1
, then look at username
, it will be "pippo"
(and it will stay "pippo"
until you do something not shown to change it). So if you're seeing null
when you expect "pippo"
, it tells you that either A) myFunction_1
has not (yet?) been called, or B) You've done something since calling myFunction_1
that set username
back to null
.
来源:https://stackoverflow.com/questions/24912542/how-do-global-variable-work-in-javascript-callback