Depth understanding _javascript techniques for scope and variable elevation (hoisting) in JS

Source: Internet
Author: User
Tags function definition

Scope (scoping)

One of the most confusing places for JavaScript beginners is the scope; in fact, not just beginners. I've seen some experienced JavaScript programmers, but they don't understand scope very deeply. The JavaScript scope is confusing because its program syntax itself is as long as the C-family language. My understanding of the scope is that it will only work on a certain range, but not the external impact of the closed space. In such a space, internal variables cannot be accessed externally, but external variables can be accessed internally.

C language variables are divided into global variables and local variables, the scope of the global variable is any file and function access (of course, for non variable definition of other C files, you need to use the extern keyword to declare, use the static keyword can also limit the scope to the current file), The scope of a local variable is a block-level range from the declaration to the nearest curly brace. Java is not a global variable, there are class variables, member variables and local variables, the scope of action according to Public,protected,private and other access rights have different scope, here is not more.

What are the JS scopes?

In ES5, JS has only two types of scopes: global scope and function scope.

Global scopes are actually scoped to global objects and can be accessed anywhere (if not covered by a function scope).

The scope of a function object is different from the scope of the local variable of C, and its scope is the entire range of functions, regardless of whether he is declared at any point in the function! This is called hoisting, the concept of variable ascension. However, in no hurry, the following will be specifically for hoisting to explain.

However, in ES6, a block-level scope (the nearest curly brace coverage) is added, but is limited to a let-way declared variable.
Scope Demo:

When you define a variable, if you do not write Var, such as i=0, it is defined as a global variable, the scope is global, otherwise it is a local variable, and the scope is a function scope. var i=0, the first line above, is said to be a global variable because it is already declared in the global area, not within the function range, and therefore is the same as i=0.

As for, why the result is so, continue to look down to know.

form of affirmation

Variable declaration:

function declaration:

Variable elevation (hoisting)

Raises a question

What does the next piece of code output?

I interviewed a lot of people for this problem and most of them said that the date was the output. But the real result is undefined. Why is that so? This leads to a conceptual--hoisting, in which Chinese means the variable ascension. The explanation for variable hoisting in MDN is this:

var hoisting

Because variable declarations (and declarations in general) are processed the any code is before, executed a declaring e anywhere in the the "Code is" equivalent to declaring it on the top. This also means so a variable can appear to be used before it ' s declared. This behavior is called "hoisting", as it appears that variable declaration be moved to the top of the function or Glo Bal code.

This passage is translated

Because variable declarations are processed before arbitrary code executes, declaring variables anywhere in the code area is the same as where the first (top) statement is declared. In other words, it looks like a variable can be used before the declaration is declared! This behavior is called "hoisting", which is the variable elevation, which looks like the declaration of a variable is automatically moved to the top of the function or global code.

Note: the definition is not elevated simply by stating that the promotion has been made.

So, the above code is actually the following form:

So, it should be understood that when the console outputs, the TMP variable is only declared but undefined, so the output should be undefined.

It should be explained here that although all declarations (including ES5 Var, function, and ES6 function *, let, const, Class) will be promoted, VAR, function, function * and let, const, Class's ascension is not the same! The specific reason can be seen in the description here (in general, although the Let,const,class is also promoted, but not initialized, this time to visit them will report Referenceerror exception, they need to execute the statement when it will be initialized, The state before being initialized is called temporal dead Zone). Let's look at a piece of code and we'll see:


Here A is promoted, but because the definition is in the post, so the output undefined

Here A has been promoted, but has reported a reference error!

And that's why

For this reason, the recommended practice is to declare the variable, write the variables that are used at the top of the scope (global scope or function scope) so that the code looks clearer, and it's easier to see if that variable comes from the scope of the function and which is from the scope chain (this article does not explain this much, Please readers themselves Baidu, have the opportunity to add the explanation).

Repeat statement

The above output is actually: 1 2 2. Although it looks like the inside X is stated two times, but it said, JS var variable only global scope and function scope two, and the affirmation will be promoted, so in fact, X will only be at the top of the place at the beginning of the statement, Var x=2 will be ignored, only for assignment. That means the code above is actually consistent with the following.

Problems of simultaneous elevation of functions and variables

What happens when a function and a variable type are defined at the same time? Look at the code below.


A

The output of the above is actually: function foo(){} the function content.

And if that's the way it is?


B

Its output turns out to be: undefined

Why is that?

The original function promotion is divided into two situations:

One: function declaration. Is above a, function foo(){} this form

Another: a function expression. Is the top B, var foo=function(){} this form

The second form is actually the declaration definition of the VAR variable, so the B output above is undefined should be understandable.

And the form of the first function declaration, when ascending, will be lifted up, including the part of the function definition! So a is equivalent to the following way!

The reason is because: 1, the function declaration is elevated to the top; 2, the assertion is only done once, so the subsequent declarations are var foo='i am text' ignored.

and the function declaration priority is better than the variable declaration, so the output of the following form is the same as the function content:

Summarize

To thoroughly understand the scope and hoisting of JS, just remember the following three points:

1. All declarations will be elevated to the top of the scope

2. The same variable is declared only once, and therefore other declarations are ignored

3, the function declaration priority is better than the variable declaration, and the function declaration will be associated with the definition of Ascension

Attention:

The WITH statement allows you to temporarily change the scope chain of the run-time context, where access to a variable that is not defined by VAR will first access the properties of the object in the with, before the property is checked up and down the scope chain.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can help, if there is doubt you can message exchange.

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.