Javascript variable escalation and closure comprehension, javascript variable escalation

Source: Internet
Author: User

Javascript variable escalation and closure comprehension, javascript variable escalation

Let's first look at a question:

<script> console.log(typeof a)//undefined var a='littlebear'; console.log(a)//littlebear </script><script> console.log(typeof a)//string var a=1; console.log(a)//1</script>

In the first script, we can see that var a is promoted to the top, and a = 'littlebear 'is kept in the original place.

The second script does not print undefined first because a has been declared by var on it, so var a will not be promoted again.

Let's look at another question:

<script>  console.log(a)//function a(){}  var a=1;  console.log(a)//1  function a(){}  console.log(a)//1</script>

We can see that function a () {} is promoted to the top. Increase the variable of the function.

1. Variable escalation

Before ES6, JavaScript has no block-level scope (a pair of curly braces {} is a block-level scope ).
Use the domain and function scope. Variable escalation refers to the first part of the scope in which the variable declaration is promoted.
Example of the previous resume:

console.log(global); // undefinedvar global = 'global';console.log(global); // globalfunction fn () {  console.log(a); // undefined  var a = 'aaa';  console.log(a); // aaa}fn();

The reason for the above printed results is that the js variable is upgraded. In fact, the above code is executed as follows:

Var global; // variable escalation within the scope of the global scope. It is declared and not assigned to the console. log (global); // undefinedglobal = 'global'; // The value is assigned to the console. log (global); // print the global function fn () {var a; // variable escalation, within the scope of function scope console. log (a); a = 'aaa'; console. log (a) ;}fn ();

2. Function Improvement

There are two methods to create a function in js: function declaration and function literal. Function upgrade is available only for function declaration! For example:

console.log(f1); // function f1() {}  console.log(f2); // undefined function f1() {}var f2 = function() {}

The reason for the above printed results is that the Code is actually executed as follows due to function improvement in js:

Function f1 () {}// function upgrade: The entire code block is upgraded to console. log (f1) at the beginning of the file; console. log (f2); var f2 = function (){}

3. What is a closure?

A closure is a function that has the right to access variables in another function scope.

Simply put, Javascript allows the use of internal functions-that is, function definitions and function expressions are located in the body of another function. In addition, these internal functions can access all the local variables, parameters, and other declared internal functions declared in their external functions. When one of these internal functions is called outside the external functions that contain them, a closure is formed.

4. Scope of Variables

To understand closures, you must first understand the scope of variables.

Variables have two scopes: global variables and local variables.

The special feature of Javascript is that the function can directly read global variables.

The internal function can access the variables of the external function because the scope chain of the internal function contains the scope of the external function;

It can also be understood that the scope of the internal function is radiating to the scope of the external function;

var n=999;function f1(){ alert(n);}f1(); // 999

On the other hand, local variables in the function cannot be read outside the function.

function f1(){ var n=999;}alert(n); // error

Note that you must use the var command when declaring variables in a function. If you don't need it, you actually declare a global variable!

function f1(){  n=999;}f1();alert(n); // 999

5. Write and usage of closures

var Circle={   "PI":3.14159,   "area":function(r){     return this.PI * r * r;   } }; alert( Circle.area(1.0) );//3.14159

At the beginning, I didn't realize that writing objects like this is also a closure. Now let's look back and think about it. This is the classic application of closures!

6. Notes for using closures

1) because the closure will make the variables in the function be stored in the memory, the memory consumption is very large, so the closure cannot be abused, otherwise it will cause the performance of the web page, memory leakage may occur in IE. The solution is to delete all unused local variables before exiting the function.

2) The closure changes the value of the internal variable of the parent function outside the parent function. Therefore, if you use the parent function as an object, use the closure as its Public Method, and use internal variables as its private value ), be sure not to change the value of the internal variable of the parent function.

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.