Details about scopes, extensions, and closures that are most confusing in JavaScript (recommended) and details about javascript

Source: Internet
Author: User

Details about scopes, extensions, and closures that are most confusing in JavaScript (recommended) and details about javascript

I. 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 reused within the entire Function range.

Function foo (a) {var B = 2; function bar (){//...} var c = 3;} bar (); // failure console. log (a, B, c); // all three failed

There are several identifiers in the above "foo" function. If you put them out of the function, an error will be reported.

2. Execute the function expression immediately.

Adding a packaging function outside any code snippet can hide internal variables and function definitions. External scopes cannot access any content inside the packaging function.

For example, the bar and a identifiers above. This protects variables from being contaminated.

When writing a plug-in, you often use immediate execution of function expressions to protect the variables in the plug-in.

var a = 2;(function foo() {var a = 3;console.log( a ); // 3})();console.log( a ); // 2

In "foo", the first () converts the function into an expression, and the second () executes this function.

There is a special term: IIFE, which indicates immediate execution of the Function Expression (Immediately Invoked Function Expression );

1. Advanced usage is to use them as function calls and PASS Parameters in

(function IIFE( global ) { var a = 3;console.log( a ); // 3console.log( global.a ); // 2})( window );

2. The purpose of a change is to invert the running sequence 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});

Ii. Block Scope

JavaScript does not support block scopes.

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 also exceptions. "try/catch" means a block scope.

Try {undefined (); // execute an illegal operation to force the creation of an exception} catch (err) {console. log (err); // It can be executed normally !} Console. log (err); // ReferenceError: err not found

ES6 changes the status quo and introduces a new let keyword. The let keyword can bind the variable to any scope (usually inside ). In other words, let implicitly declares the block scope for its variables.

Iii. Improvement

The function scope and block scope have the same behavior. We can conclude that any variable declared in a specific scope will be attached to this scope.

1) Compilation and execution

All declarations of variables and functions are processed before any code is executed. You can refer to the following code example.

a = 2;var a;console.log(a);//2

This code is equivalent:

Var a; // The definition declaration is a = 2 in the compilation phase; // The Value assignment declaration will be left in the original place waiting for the execution phase console. log ();

2) function priority

The function is promoted first, and then the variable.

foo(); // 1var foo;function foo() {console.log( 1 );}foo = function() {console.log( 2 );};

The var foo function expression appears before the declaration of function foo (), but it is a repeated declaration (so it is ignored), because the function declaration will be promoted to the normal variable.

The above code is equivalent:

function foo() {console.log( 1 );} foo(); // 1foo = function() {console.log( 2 );};

Iv. Closure

A closure is a function that has the right to access variables in another function scope. The most common way to create a closure is to create another function in one function,
Using another function to access the local variables of this function, the closure can break through the function Chain Domain and pass the internal variables and methods of the function to the external

Closure features:

1. nested Functions

2. Internal functions can reference outer parameters and variables.

3. Parameters and variables are not recycled by the garbage collection mechanism.

1) Definition

When a function can remember and access its scope, 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 can be executed.

2. The closure will also prevent garbage collection. After "foo" is executed, the internal scope will still exist. In this way, "baz" can be executed.

2) passing functions as parameters

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. When calling this internal function (fn), the closure of the foo () internal scope covered by it can be observed because it can access.

If you use a function as the first-level value type and pass it everywhere, you will see the application of the closure in these functions.

When a callback function is used in a timer, event listener, Ajax request, cross-window communication, Web Workers, or any other asynchronous (or synchronous) task, the closure is actually used!

3) loops and closures

for (var i = 1; i <= 5; i++) {setTimeout(function timer() {console.log(i);}, i * 1000);}

Each printing will be 6, and the callback of the delay function will be executed at the end of the loop.

According to the working principle of the scope, the actual situation is that although the five functions in the loop are defined separately in each iteration, they are all closed in a shared global scope, therefore, there is actually only one I.

Now we use closures to print different I values each time.

for (var i = 1; i <= 5; i++) {(function(j) {setTimeout(function timer() {console.log(j);}, j * 1000);})(i);}

IIFE creates a scope by declaring and immediately executing a function. The callback in setTimeout can remember the current scope. The parameter "j" in each scope is different.

The above is a detailed description of the most confusing scope, upgrade, and closure knowledge in JavaScript provided by xiaobian. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.