1. Function scope
1. Function scope
It means that the scope is in a "Function", and all variables belonging to this function can be used and multiplexed within the entire function scope.
function foo(a) {var b = 2;function bar() {// ...}var c = 3;}bar(); // Failed console.log( a, b, c ); // All three failedIf several identifiers in the "foo" function above will be reported if they are placed outside the function and accessed.
2. Execute function expression immediately
Adding wrapper functions outside any code snippet can "hide" the internal variables and function definitions, and the external scope cannot access anything inside the wrapper function.
For example, the above bar, a and other identifiers. This will protect the variable from contamination.
When writing plug-ins, you often use immediately to execute function expressions to protect the variables inside.
var a = 2;(function foo() {var a = 3;console.log( a ); // 3})();console.log( a ); // 2The first ( ) in "foo" turns the function into an expression, and the second ( ) executes this function.
There is a special term: IIFE, which represents the Immediately Invoked Function Expression;
1. Advanced usage is to call them as function and pass parameters in
(function IIFE( global ) { var a = 3;console.log( a ); // 3console.log( global.a ); // 2})( window );2. A changing purpose is to invert the running order of the code, which is widely used in CMD or AMD projects.
(function IIFE(factory) {factory( window );})(function def( global ) {var a = 3;console.log( a ); // 3console.log( global.a ); // 2});2. Block scope
JavaScript does not support block scope.
for(var i=0; i<10; i++) {console.log( i );}The "i" in the above code is equivalent to the following
var i;for(i=0; i<10; i++) {console.log( i );}But there are exceptions, "try/catch", catch is a block scope.
try{undefined(); // Execute an illegal operation to force an exception} catch(err) {console.log(err); // Can execute normally! }console.log( err ); // ReferenceError: err not foundES6 has changed the status quo and introduced a new let keyword, which can bind variables to any scope (usually inside { .. }). In other words, the variables declared for let implicitly lie in the block scope.
3. Improvement
The behavior of function scope and block scope is the same, and can be summarized as: any variable declared within a scope will be attached to this scope.
1) Compilation and execution
All declarations of variables and functions will be processed first before any code is executed. You can see the following code example.
a = 2;var a;console.log(a);//2
This code is equivalent to:
var a;//Definition declaration is performed in the compilation stage a = 2;//Assignment declaration will be left in place to wait for the execution stage console.log(a);
2) Function priority
The function will be promoted first, and then the variable will be.
foo(); // 1var foo;function foo() {console.log( 1 );}foo = function() {console.log( 2 );};The var foo function expression, although before the declaration of function foo(), is a duplicate declaration (and therefore ignored), because the function declaration will be promoted before the normal variable.
And the above code is equivalent to:
function foo() {console.log( 1 );} foo(); // 1foo = function() {console.log( 2 );};4. Closure
Closures refer to functions that have access to variables in another function scope. The most common way to create closures is to create another function within one function.
Accessing local variables of this function through another function, using closures can break through the action chain domain and pass variables and methods inside the function to the outside
Closure features:
1. Functions are inherently nested
2. Internal functions can refer to outer parameters and variables
3. Parameters and variables will not be collected by the garbage collection mechanism
1) Definition
When a function can remember and access the scope it is located, a closure is generated, even if the function is executed outside the current scope.
function foo() {var a = 2;function bar() { console.log( a );}return bar;}var baz = foo();baz(); // 2 ― This is the effect of the closure.1. Assign the function "bar" to "baz" and execute "baz". The current scope is not in the scope of "bar", but it can be executed.
2. The closure will also prevent garbage collection. When the "foo" is executed, the internal scope still exists. This way, the "baz" can be executed.
2) Pass the function as a parameter
function foo() {var a = 2;function baz() {console.log( a ); // 2}bar( baz );}function bar(fn) {fn(); // This is the closure! }Pass the internal function baz to bar, and when this internal function is called (fn), the closure of the internal scope of foo() it covers can be observed because it can access a.
If you treat a function as a value type at the first level and pass it everywhere, you will see the application of closures in these functions.
In timers, event listeners, Ajax requests, cross-window communication, Web Workers or any other asynchronous (or synchronous) tasks, as long as the callback function is used, it is actually using closures!
3) Loops and closures
for (var i = 1; i <= 5; i++) {setTimeout(function timer() {console.log(i);}, i * 1000);}Every time it is printed, it will be 6, and the callback of the delay function will be executed only at the end of the loop.
According to how scope works, the reality is that although the five functions in the loop are defined separately in each iteration, they are all enclosed in a shared global scope, so there is actually only one i.
Now use closures to implement the different i printing each time.
for (var i = 1; i <= 5; i++) {(function(j) {setTimeout(function timer() {console.log(j);}, j * 1000);})(i);}IIFE creates scopes by declaring and executing a function immediately. The callback in setTimeout can remember the current scope, and the parameter "j" in each scope is different.
The above is a detailed explanation of the most confusing scope, improvement, and closure knowledge in JavaScript that the editor introduces to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!