js note closure (Closure)

1. Variable scope

1. Global variables

1. Global variables can be used inside the function
2. Local variables in the function cannot be used outside the function
3. When the function is executed, the local variables in the scope will be destroyed

2. Local variables

1. The inside of the function is the local variable

2. Closure

Closures are functions that have access to variables in the scope of another function.
(That is, one scope can access the local variable inside another function.)
If there is a local variable a inside a function, other scope b (whether it is a global scope or a local scope) can access this local variable a , There will be closures at this time.
Then the function in which this variable a is located is called a closure function.
The main function of the closure: extends the scope of the variable.
But closures can also cause memory leaks.

1. The first type

 <script>
     // 闭包:fun 这个函数作用域访问了另外一个函数fn 里面的局部变量 num,此时就产生了闭包,而被访问的局部变量num所在的函数fn就是闭包函数
     // fn 外面的作用域可以访问fn 内部的局部变量
     function fn() {
    
    
         var num = 10;

         function fun() {
    
    
             console.log(num);
         }
         fun();
     }
     fn();
 </script>

2. The second type

(The scope outside the function accesses the local variables inside the function)

 <script>
// fn 外面的作用域可以访问fn 内部的局部变量
function fn() {
    
    
	var num = 10;

	function fun() {
    
    
		console.log(num);
	}
	// fun 不加括号就相当于一个变量,也就是相当于fun的整体
	// 函数是一种数据类型,所以可以当参数,也可以当返回值
	return fun;
}
// 此时就实现了fn函数外面的作用域可以访问fn内部的局部变量了
var f = fn();
f();

 /*
  1、fn() 这个函数一调用,就会执行 function fn(){}  => var num = 10;  => function fun(){}不调用不执行
  ==> 执行return fun; 
  类似于 var f = function fun() {
                     console.log(num);
                 }
  ==> 此时 f 存的是一个函数 => 此时就可以调用f 这个函数 f();  =>调用了f();它就会到function fun(){}
  ==>function fun(){} 里面的num 因为在函数fn 里面,所以可以使用fn函数的变量,
  ==> 所以调用f 就可以打印出num
  */
 </script>

3. Common interview questions for closures

	<body>
		<ul class="nav">
			<li>1</li>
			<li>2</li>
			<li>3</li>
			<li>4</li>
		</ul>
		<script>
			// 利用闭包的方式得到当前li的索引号
			var lis = document.querySelector('.nav').querySelectorAll('li');
			for(var i = 0; i<lis.length; i++){
     
     
				// 利用for循环创建了四个立即执行函数
				(function(i){
     
     
					lis[i].onclick = function(){
     
     
						console.log(i);
					}
				})(i);
			}
		</script>
	</body>

Guess you like

Origin blog.csdn.net/weixin_44401120/article/details/113939901