JavaScript-detailed scope and application

One, scope overview

1. Generally speaking, the name used in a piece of program code is not always valid and usable, and it 可用性的代码范围is this name that defines the name 作用域. The use of scope improves the locality of program logic, enhances program reliability, and reduces name conflicts.
2. Before the scope of js (es6): 全局作用域 局部作用域
3 全局作用域.: The entire script tag, or a single js file
4 局部作用域.: Inside the function is the local scope, the name of this code only has an effect and effect inside the function

Second, the scope of variables

2.1 Classification of variable scope

In JavaScript, variables can be divided into two types according to the scope: 全局变量和局部变量
1. Global variables: Variables in the global scope can be used in the global scope.
Note:如果在函数内部没有声明直接赋值的变量也属于全局变量(前面不加 var)

<script>
	var num = 10;//num此时就是一个全局变量
	console.log(num)
	
	function fn(){
    
    
	console.log(num)//在局部函数中也可以调用全局变量
    }
    fn();
</script>

2. Local variables: variables in the local scope, or variables inside the function are local variables.
Note:函数的形参也可以看做是局部变量

function fn(){
    
    
	var num = 10;//此时num就是局部变量只能在函数内部使用,在外面输出不了
	console.log(num)
    }
    fn();

3. From the perspective of execution efficiency, global variables and local variables

  1. Global variables can be used in any place, and will only be destroyed when the browser is closed, which takes up more memory resources
  2. Local variables are only used inside the function, and will be destroyed when our program is executed, which saves memory resources

Three, scope chain

  1. As long as it is code, there is at least one scope
  2. What is written inside the function is the local scope
  3. If there are functions in the function, then another scope can be born in this scope
  4. According to this mechanism that internal functions can access external function variables, chain search is used to determine which data can be accessed by internal functions, which is called scope chain (principle of proximity)
function fn(){
    
    //外部函数
	var num = 20;
	function fun(){
    
     //内部函数

     }
}

案例1: What is the result?

function fn1(){
    
    
	var num = 123;
	function fn2(){
    
    
	console.log(num);
}
fn2();
}
var num = 456;
fn1();

案例2: What is the result?

var a=i;
function fn1(){
    
    
	var a = 1;
	var b = '10';
	fn2();
	function fn2(){
    
    
		var a=3;
		fn3();
		function fn3(){
    
    
      	var a = 4;
      	console.log(a);//a的值?
      	console.log(b);//b的值?
      }
    }
}
fn1();

Guess you like

Origin blog.csdn.net/weixin_45054614/article/details/107737957