Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
278 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...