The most confusing scope, promotion, and closure knowledge in JavaScript (recommended) _javascript tips

Source: Internet
Author: User
Tags closure garbage collection wrapper

I. Scope of functions

1. Function scopes

Is that the scope is in a "function" where all variables belonging to this function can be used and reused throughout the function.

function foo (a) {
var b = 2;
function Bar () {
//...
}
var c = 3;
}
Bar (); Failure
Console.log (A, B, c);//Three All failed

Several identifiers in the "foo" function above, placed outside the function, will have an error.

2. Execute function expression now

Adding wrapper functions outside of any code fragment allows you to "hide" internal variables and function definitions, and external scopes cannot access any content inside the wrapper function.

For example, the above bar, a, and several other identifiers. This will protect the variable from being contaminated.

When you write plug-ins, you often use the immediate execution function expression to protect the variables inside.

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

The first () in "foo" turns the function into an expression, and the second () executes the function.

There is a special term: Iife, which represents the immediate execution of a function expression (Immediately invoked functions Expression);

1. Advanced usage is to call them as functions and pass arguments in.

(function Iife (global) { 
var a = 3;
Console.log (a); 3
Console.log (GLOBAL.A);//2
}) (window);

2. A change in the use of inverted code is the order of operation, in the CMD or AMD project is widely used.

(function Iife (factory) {
Factory (window);
}) (Function def (global) {
var a = 3;
Console.log (a); 3
Console.log (GLOBAL.A);//2
});

Two, block scope

JavaScript does not support block scopes.

for (var i=0; i<10; i++) {
console.log (i);
}

The "I" in the code above is equivalent to the following

var i;
For (i=0 i<10; i++) {
console.log (i);
}

But there are exceptions, "Try/catch", and catch is a block scope.

try{
undefined ();//Perform an illegal operation to force an exception 
} 
catch (err) {
console.log (err);//be able to perform properly!
}
Console.log (ERR); Referenceerror:err not found

ES6 changed the status quo by introducing a new let keyword, which binds the variable to any scope (usually {...}). Internal). In other words, the variable declared by let is implicitly the block scope in which it is located.

Third, the promotion

The function scope and block scope behave the same, and can be summed up as follows: Any variable declared within a scope will be attached to this scope.

1) Compilation and execution

All declarations of variables and functions are processed first before any code is executed, and you can look at the following code example.

A = 2;
var A;
Console.log (a);//2

This piece of code is equivalent to:

The Var a;//definition declaration is performed during the compile phase
a = 2;//assignment declaration will be left in place pending execution phase
Console.log (a);

2) function First

The function is first promoted and then the variable.

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

The var foo function expression, although appearing before the Declaration of function foo (), is a duplicate declaration (and therefore ignored) because the function declaration is elevated before the normal variable.

And the code above is equivalent to:

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

Four, closures

Closures are functions that have access to variables in the scope of another function, and the most common way to create closures is to create another function within one function,
By accessing the local variables of this function through another function, the closure can be used to break through the scope of the function and pass the variables and methods inside the functions to the external

Characteristics of closures:

1. function intrinsic nesting function

2. Internal functions can refer to outer parameters and variables

3. Parameters and variables will not be recycled by garbage collection mechanism

1) definition

When a function can remember and access the scope in which it resides, a closure occurs, 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 closures.

1. Assign the function "bar" to "Baz", execute "Baz", the current scope is not in the scope of "bar", but can be executed.

2. Closures also prevent garbage collection, and when "foo" is done, the internal scope still exists. This will allow the "Baz" to execute.

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!
}

By passing the internal function Baz to bar, when the intrinsic function is invoked (FN), it covers the closure of the inner scope of the Foo (), which can be observed because it accesses a.

If you use a function as a first-level value type and pass it around, you'll see the closure's application in these functions.

In timers, event listeners, AJAX requests, cross Windows communications, WEB workers, or any other asynchronous (or synchronous) task, using a callback function is actually using a closure!

3 Loops and closures

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

Every time you print it, it will be 6, and the callback for the delay function will not be executed until the end of the loop

Depending on how the scope works, the reality is that although the five functions in the loop are defined separately in each iteration, they are closed in a shared global scope, so there is actually only one I.

Now with the closure to achieve each printing different I.

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. Callbacks in SetTimeout can remember the current scope, and the parameter "J" in each scope is different.

The above is a small set of JavaScript to introduce the most easily confused scope, promotion, closure knowledge, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.