Global and local scope in javascript
The scope is a programming concept. The names used in a piece of program code is not always valid/available, and the scope of the code that limits the availability of the name is the scope of the name.
The use of scope improves the locality of the program logic, enhances the reliability of the program and reduces name conflicts.
1. Global scope (global variables)
Global variables, the principle is to mount the variables to the window object. Global variables have a global scope and can be called anywhere. There are two ways to declare global variables
(1) Outside the function
(All the variables written outside the function are global variables)
var num = 15 ; //Global variable
function f () {
var num = 10 ; //Not a global variable
function f2 () {
/*----*/
} f2();
}f(); console .log(num); // 15
(2) Inside the function
(Variable declaration without var, implicit global variable)
2. Local scope
//Inside the Function
function f () {
num = 10 ; //implicit global variable
}
f(); console .log(num); // 10 Local variables: variables written in the function body
Local variables can only use
<script>
function f () {
var num = 10 ; //local variable function
f2 () { console .log(num); // 10 }
f2(); }
f(); console .log(num); // not defined
< /script>
scope chain
In short, the scope chain is that when calling a variable, if there is no such variable in the current scope, it will look for its upper-level scope.
Javascript uses a static scope
Example:
/* Level 0 scope*/
var a = 1 ;
function aa () { /* Level 1 scope*/ //
var a = 2;
function bb () { /* Level 2 scope*/ //
var a = 3;
console .log(a); // 1
}
bb(); }
aa();