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
184 views
in Technique[技术] by (71.8m points)

javascript - Why does local variable kill my global variable?

Sorry for this question, but this issue really screwed up my day.

The following Code alerts 10 as it should:

var globalId='10';  
function check(){  
    alert(globalId);  
}  
check();

But this next code alerts undefined:

var globalId='10';  
function check(){  
    alert(globalId); 
    var globalId; 
}  
check();

I am aware that if I declare a variable in a function its a local variable, but if I already declared it as global, how can it be that my alerts says undefined?

This is an easy example, but in my original code I did a lot of stuff in between the beginning of the function, then a long way down I checked to see if globalId was defined, else define it: if(!globalId){var globalId;} This meant that my alert situated at the top of the function generated undefined, as if JavaScript first executed the whole function, just to see if any variables 'might' be declared, and if so, declare them and therefore my alert pointed to an 'undeclared' variable.

Can anybody explain to me why this happen, and if it is true that JavaScript "pre-declares" all variables before executing a function, even variables declared in conditions not even met?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In javascript, you should know there is something called as HOISTING.

What this essentially means is, when you declare any local variables, the variable declaration is automatically carried to top of the scope.

eg:-

var globalId='10';
function check(){
alert(globalId); var globalId; }
check(); 

Changes to -

var globalId='10';
function check(){
var globalId;
alert(globalId);}
check(); 

Since globalID is still not assigned any value, it returns undefined in your output. The local variables always get priority over the global variables with same name.


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

...