Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

forms - How do global variable work in javascript (callback)?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...