JavaScript mimics block-level scopes with anonymous functions

Source: Internet
Author: User
Tags anonymous closure

There is no block level scope concept in JavaScript. This means that the variables defined in the block statement are actually created in the containing function rather than in the statement.

function Outputnumbers (count) {for
(var i = 0; i < count; i++) {
alert (i);
}
Console.log (i);
}
Outputnumbers (2);//Eject 0,1 output 2
//variable i is defined in the active object of outputnumbers (), so it can be accessed at any time within the function, starting with its definition.


Multiple declarations in a function, JavaScript will only ignore subsequent declarations for multiple declarations of the same variable.

function Outputnumbers (count) {for
(var i = 0; i < count; i++) {
alert (i);
}
var i;
Console.log (i);
}
Outputnumbers (2);//eject 0,1 output 2


Resolution

Transition Writing first creates an anonymous function, assigns the anonymous function to the variable somefunction, and then invokes the function by adding a pair of parentheses after the function name.

var someFunction = function () {
   //This is a block-level scope
};
SomeFunction (); An anonymous function such as

Error writing can have an error directly with parentheses, because JavaScript treats the Function keyword as the beginning of a function declaration, and the function declaration cannot be followed by the parentheses

function () {
    //This is a block-level scope
} ()//Error

"correct" and the function expression can be followed by parentheses, to convert the function declaration to a function expression, just give the function a whole set of parentheses.

(function () {
   //This is block-level scope
}) ();
Defines and immediately calls an anonymous function. Include a function declaration in a pair of parentheses, indicating that it is actually a function expression. A second pair of parentheses immediately following this function is called.

Workaround

Set block-level scope inserts a private scope outside the for loop in the overridden Outputnumbers () function. Any variables defined in an anonymous function are destroyed at the end of execution. Therefore, the variable I can only be used in loops.

function Outputnumbers (count) {
(function () {for
var i = 0; i < count; i++) {
alert (i        );
}
) ()
console.log (i);
}
Outputnumbers (2);//Eject 0, 1, and then error, prompt i is not defined


Application Scenarios

This technique is often used outside of a function in the global use domain, limiting the addition of too many variables and functions to the global scope. By creating a private scope, each developer can use its own variables without worrying about messing up the global scope.

(function () {
var now = new Date ();
if (now.getmonth () = = 0 && now.getdate () = = 1) {
alert ("Happy new year!");
}
})();
The variable now in code is a local variable in an anonymous function and does not have to be created in the global scope.



Benefits

This approach reduces the memory footprint of closures because there is no reference to anonymous functions, and as long as the anonymous function completes, the scope chain can be destroyed immediately.



JS Impersonation Block Level scope

No block-level scopes and how to simulate block-level scopes

JavaScript is not a block-level scope, as the following can be verified:

if (true) {
var name = ' Xiaofei ';
}
Console.log (name); Xiaofei for
(var i = 0; i < i++) {
//do something
}
console.log (i);//10


So how do you simulate block-level scopes? Anonymous functions can be used to simulate block-level scopes

(function () {
//the variable defined here will be destroyed at the end of the Run
}) ();
//See example:
function Fun (n) {
(function () {for
(var i = 0; i < n; i++) {
//do    Mething
}
) ();
Console.log (i); Unable to access error occurred
}


Explanation: The internal variables are immediately destroyed after the anonymous function inside the fun function has been run, so I cannot be accessed outside of the anonymous function
Also note that creating an anonymous function inside the fun function essentially creates a closure, but the closure does not pay the other variables and there is no reference.
So it's destroyed immediately after it's done.


JavaScript anonymous function (impersonation block-level scope)

There is no block-level scope concept in JavaScript. That is, a variable that is defined in a block-level statement is actually created in the containing function (the external function) rather than in the statement.

function Outputnumber (count) {for
(var i=0;i<1000;i++) {
alert (i);   
}  
alert (i); Count
}


The function in Java, C # and other languages, the variable I will only be defined in the FOR Loop statement, Loop end, I was destroyed. But in JavaScript, the variable i is defined in the Outputnumber () active object, so it can be accessed within the function as soon as it is defined. Even if you re declaring the same variable, it doesn't change its value.

function Outputnumber (count) {for
(var i=0;i<1000;i++) {
alert (i);   
}  
var i;   Re-declare Variable
alert (i); Count
}


Anonymous functions can be used to mimic block-level scopes and to avoid this problem, and the syntax for anonymous functions used as block-level scopes (also known as private scopes) is as follows:

(function () {
//This is block-level scope
}) ()


The code definition above uses an anonymous function that contains a function declaration inside a parenthesis to indicate that it is a function expression. This function is called immediately after the other pair of parentheses.

Whenever you need some variables temporarily, you can use a private scope, such as:

function Outputnumber (count) {
(function () {for
(var i=0;i<1000;i++) {
alert (i);
})  ();   
alert (i); Cause an error
}


In this way, we insert a private scope outside of the For loop. Any variables defined in an anonymous function are destroyed at the end of execution.

This technique is often used outside of a function in the global scope, limiting the addition of too many variables and functions to the global scope.

In general, we should minimize the addition of variables and functions to the global scope.

This approach reduces the need for closures to consume memory because there is no reference to anonymous functions, and the scope chain can be destroyed immediately as soon as the function has finished executing.

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.