<textarea class="ace_text-input"></textarea>```It's very obvious that the first pop- out box didn't have as i wanted to bounce Global and it's undefined . Why is that ? It is by the function of the domain specificity function fields are better than all local with name change volume cover all board Span class= "ACE_CJK" to The scope of the first alert is not yet well - defined To undefined the code can be solved as follows: ```function f () {var scope;alert (scope);var scope = "local";alert (scope); };f ();// equal price and The sound of the variable in the function of the " before" to the function of the body Top Department ```
- Xiaonine
- File
- Publish Updates
The scope of the variables of the JavaScript learning Diary
javascript学习日记
变量的作用域是往往是人们轻易忽略而又至关重要的问题,尤其是在javascript中。
The scope of variables in JavaScript has the following characteristics:
- function domain with function division
- No specific block scope
- A variable that is not declared with VAR is a global variable
Let's look at a specific example:
var global =1;
function f(){
var local = 2;
global++;
return global;
}
alert(f()) ;//2
alert(f()) ;//3
alert(window.local);//undefined
The code can be seen declaring a global variable and a local variable locally;
and the function f () can access the outside global variables globally;
But local variables outside of the function f () do not exist locally
It is obvious that the code inside the function accesses the global variable as if it were accessing local variables.
Otherwise it's not.
2 Declaration of Function Scope advance issue
先来看如下代码:
var scope ="global";
function f(){
alert(scope);//undefined
var scope ="local";
alert(scope);//local
}
f();
Apparently the first pop-up didn't appear as I wanted to pop the global but undefined
What is this for?
In fact, due to function scope characteristics
The function domain is always better than the global domain
Local variables with the same name override global variables
And the first call to alert scope is not formally defined as undefined
The above code can be understood as:
function f(){
var scope;
alert(scope);
var scope ="local";
alert(scope);
};
f();
//等价与函数内变量的声明‘提前‘至函数体顶部
@XiaoNine
2016-11-20 10:14
字数
阅读 8
The scope of the variables of the JavaScript learning Diary