Learning JavaScript with me var pre-parsing and function declaration promotion _javascript Skills

Source: Internet
Author: User
Tags function definition

1. Pre-compiling var variable

JavaScript syntax is similar to C, Java, and C #, collectively known as Class C syntax. Students with C or Java programming experience should be familiar with the "declare first, then use" rules, if the use of undeclared variables or functions, in the compile phase will be an error. However, JavaScript is able to use variables and functions before they are declared. Let's take a closer look at the mystery.

Let's look at a piece of code:

(function () {
 console.log (nosuchvariable);//referenceerror:nosuchvariable is not defined
}) ();

Running the above code immediately complains, however, this is what we expect, because the nosuchvariable variable is not defined at all! Take another look at the following code:

(function () {
 console.log (declaredlater);//undefined
 var declaredlater = "Now it's defined!";
 Console.log (declaredlater);//"Now it's defined!"
}) ();

First of all, the above code is correct, there is no problem. But, why not the error? is the declaredlater variable defined after the calling statement? Why is it that the output is undefined?

This is actually a JavaScript parser. The parser places all the variables and functions declared within the current scope at the beginning of the scope, but only the declaration of the variable is advanced to the beginning of the scope, and the assignment is left in place. The above code for the parser is actually the following:

(function () {
 var declaredlater;//Declaration was advanced to the scope start!)
 Console.log (Declaredlater);//undefined
 declaredlater = "Now it's defined!";//assignment operation still in place!
 Console.log (declaredlater);//"Now it's defined!"
}) ();

This is why the above code does not report the cause of the exception! After the variables and functions have been "advanced", the Declaredlater variable is actually placed in front of the calling function, and, according to the JavaScript syntax, the declared and unassigned variables are automatically assigned to undefined, so the first time you print The value of the Declaredlater variable is undefined, and then we assign the Declaredlater variable, so the second time the print variable prints the now it ' s defined!.

Let's look at one more example:

var name = "Baggins";
(function () {
 console.log ("Original name was" + name);/"Original name was undefined"
 var name = "Underhill"; C11/>console.log ("New name is" + name);/"New name is Underhill"
}) ();

In the above code, we first declare a variable name, we would like to print the first time the name variable can output the global scope definition of the name variable, and then in the function to define a local name variable overwrite global variables, and finally output the value of local variables. But the result of the first output was completely inconsistent with our expectations because the local variable we defined was "advanced" in its scope, which became the following form:

var name = "Baggins";
(function () {
 var name;//NOTE: The name variable is advanced!
 console.log ("Original name was" + name);/"Original name was undefined"
 name = "Underhill";
 Console.log ("New name is" + name);/"New name is Underhill"
}) ();

Because JavaScript has such "quirks", it is recommended that you place variable declarations at the top of the scope, so that you can always remind yourself.

2, function declaration "be Advanced"

The front is the variable, and then we'll talk about the function.

The "being advanced" of a function is divided into two cases, one being the function declaration and the second being the function as a value assigned to a variable, or a function expression.

First of all, on the code:

Isithoisted ()//"yes!"
function isithoisted () { 
 console.log ("yes!");
}

As shown above, the JAVASCRIPT interpreter allows you to use before a function declaration, that is, a function declaration is not just a function name "being advanced", and the entire function definition is "advanced"! So the code above can be executed correctly.

Let's look at the second case: the form of a function expression. Or the first code:

Definitionhoisted ()//"Definition hoisted!"
Definitionnothoisted ()//typeerror:undefined is not a function
function definitionhoisted () { 
 console.log () Definition hoisted! ");
}
var definitionnothoisted = function () { 
 console.log ("Definition not hoisted!");

We made a comparison that the definitionhoisted function was properly executed, conforming to the first type; the definitionnothoisted variable was "advanced", but his assignment (i.e. the function) was not advanced, and from this point on, This is exactly the same as the previous variable "being advanced", and because the default value of the "forward" variable is undefined, the reported error is "Type mismatch" because undefined is not a function and certainly cannot be invoked.

Summarize
The above explanation can be summarized as follows:

The declaration of the variable is advanced to the top of the scope and the assignment remains in place
function declaration whole "be Advanced"
function expression, only the variable is "advanced", the function is not "advanced"
3, Var's side effects

There is a small difference between an implicit global variable and a well-defined global variable, the ability to make a variable undefined by the delete operator.

Global variables created through VAR (created in programs outside of any function) cannot be deleted.
Implicit global variables that are not created by Var (regardless of whether they are created in a function) can be deleted.
This shows that, technically, implicit global variables are not true global variables, but they are properties of global objects. Properties can be deleted by the delete operator, and the variable is not available:

Defines three global variables
var global_var = 1;
Global_novar = 2;  Negative example
(function () {
 global_fromfunc = 3;//Negative Example
} ());

Attempt to delete delete
Global_var;  False
Delete Global_novar;//True
delete Global_fromfunc;//True

//test the deletion
typeof global_var;< c14/>//"number"
typeof Global_novar;//"undefined" typeof
Global_fromfunc;//"Undefined"

In ES5 strict mode, undeclared variables, such as the two negative cases in the previous code fragment, throw an error.

4. Declaring variables in single var form

Using a single VAR statement at the top of a function is a more useful form, and the benefit is:

Provides a single place to find all the local variables needed for the function
Logic errors that prevent variables from being used before they are defined
Less code (type AH pass the value Ah single completed)
The single var form looks like this:

function func () {
 var a = 1,
  b = 2,
  sum = a + b,
  myobject = {},
  I,
  J;
 function body ...
}

You can use a var statement to declare multiple variables, separated by commas. It is good to initialize the values at the same time as this initialization variable. This can prevent logical errors (the initial value of all uninitialized but declared variables is undefined) and increase the readability of the code. After you see the code, you can know the approximate purpose of these variables based on the value of the initialization.

The above is for the JavaScript of the Var pre-resolution and function statement to promote the learning content, I hope to help you learn.

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.