Front-end JS study notes (1)

Triggering and resolution of closures

1. Trigger situation: There are functions inside the function, and the closure will occur when the internal function is saved to the outside.
2. Use a simple example to show:
<script>
	function test() {
     
     
	    var arr = [];
	    for(var i = 0; i < 10; i ++){
     
     
	
	        arr[i] = function (){
     
     
	          document.write(i + ' ');
	        }
	
	    }
	    return arr;
	}
	
	var Myarr = test();
	for(var i = 0; i < 10; i ++){
     
     
	  Myarr[i]();
	}
</script>

Running result:
10 10 10 10 10 10 10 10 10 10

  • Analysis: I want to assign a function to each bit of the array that can print the current array subscript, but the function is not executed when it is defined. When the array is saved to the outside, the i in the function has become 10.
3. Solution: execute the function immediately
<script>
 function test() {
     
     
	var arr = [];
	
	for(var i = 0; i < 10; i ++) {
     
     
	    (function(j) {
     
     
	        arr[j] = function () {
     
     
	            document.write(j + ' ');
	        }
	    }(i))
	}
	return arr;
}

var Myarr = test();
for(var i = 0; i < 10; i ++) {
     
     
	Myarr[i]();
}
</script>

Operation result:
0 1 2 3 4 5 6 7 8 9

  • Analysis: If you want the subscript of the array to be saved in real time, you should use the immediate execution function to assign the current value of i to the formal parameter j, then Myarr can get the scope chain of each array member to get j when it is assigned value.

Guess you like

Origin blog.csdn.net/weixin_45688536/article/details/108160911