1. Function scope
1. Two different script tags. First, execute all the previous code, and the later script can use the previous script variable
2. It is unreasonable to execute from top to bottom in the same script
/* In the same scope (code execution steps): 1,Definition var a(Define variables) Definition of function (definition of named function) 2,Execution (except that the definitions are all execution, from top to bottom) */ alert(a);//undefind var a = 'Nan Nan';
2. New scope and scope chain
New scope:
Every time a new scope is encountered, new definition and execution steps will be started. After the new scope is executed, it will return to the parent scope to continue execution;
Scope chain:
When a variable is encountered during execution, it will be found in the current scope. If it is not found, it will be found from the parent. If it is not found all the time, it will return undefined (Note: undefined is found, but there is no assignment). The parent cannot find the variable from the child
var name = 'one after another'; function fn(){ console.log(name); //undefined var name = 'Nan Nan'; console.log(name); //Nan Nan } fn();
3, closure
/* Closure: inter Functions can persist the environment in which they are defined. When they are called, they will remember their environment, And the declared variables and environment are encapsulated into a closed environment, which we call "closure"; A function is also a closure */ function outer(){ var a = 3; function inter(){ console.log(a); } return inter; } var fna = outer();//inter fna();
Nature of closure:
1. Every time a function is re referenced, the closure is brand new;
Most commonly used closures:
<style> #box{ width: 500px; margin: 100px auto; } #box p{ width: 100px; height: 100px; background-color: #ccc; margin: 10px; float: left; } </style> <body> <div id='box'> <p>1</p> <p>2</p> <p>3</p> <p>4</p> </div> </body> <script> /* Case 1 (using functions to store variables)*/ var aP = document.querySelectorAll('p'); for(var i=0;i<aP.length;i++){ (function (m) { aP[m].onclick = function () { alert(m+1); } })(i); } /* Case 2 (define new attributes to store variables)*/ var aP = document.querySelectorAll('p'); for(var i=0;i<aP.length;i++){ aP[i].index = i+1; aP[i].onclick = function(){ alert(this.index); } } </script>
Operation result chart: (click the corresponding box to pop up the corresponding number)