1. Scope
1.1 Scope Overview
In general, a program code that used the name are not always effective and available. And with the code name given to this range is the availability of the scope of this name.
Use scope to improve the local logic program. Enhancing the reliability of the program, the name of reducing conflict.
< Head > < Meta charset = "UTF-. 8" > < Meta name = "the viewport" Content = "width = width-Device, Initial-Scale = 1.0" > < title > the Document </ title > < Script > // the JS scope: it is the code (variable) name within a certain range and effectiveness of work programs aimed at improving reliability and reducing program naming conflicts // JS scopes into global scope and local scope before (ES6) / / 1. entire script tag has global scope or use a separate JS file. var NUM = 10 ; the console.log (NUM); // 10 // 2. local scope inside the function is the name of local scope of this code within the function only work function Fn () { // local scope var NUM = 0 ; console.log(num);//0 } fn(); </script> </head>
2 variable scope
2.1 Classification of variable scope
In JavaScript, depending on variable scope can be divided into two types:
1. Global Variables
2. Local variables
< Head > < Meta charset = "UTF-. 8" > < Meta name = "the viewport" Content = "width = width-Device, Initial-Scale = 1.0" > < title > the Document </ title > < Script > // The we scoped variables into different global and local variables // 1 global variables throughout the Script tab or the entire document can be used js // Note that if there is no direct assignment statement within the function of the situation but must belong to a global variable after the function is executed to effectively var NUM = 10 ; // global variables console.log (num); function fn() { console.log(num); } fn(); // 2 Variables Local variables in local scope // Note that the function of the variable parameter is the local function Fun () { // local variables can not be used outside var SUM = 0 ; sum2 = 20; } // fun(); console.log(sum2); // From a performance point of view the global and local variables // 1. global variables only when the browser is closed will be destroyed comparison of total memory resources // 2. Local variables When we finished the program will compare the destruction to save memory resources </ Script > </ head >
js not block-level scope but only after a block-level scope es6 example of Swift or OC {} variable is declared scope is the block-level scope in braces.
But not before the JS es6.
3 scope chain
As long as there is at least a scope code
Written inside the function's local scope
If the function then there are functions in this scope but also the birth of a scope
According to internal functions can access external mechanisms function variables with which data can be chained inside a function called Find decided to visit the scope chain