Learn how to use javascript var pre-parsing and function declaration to improve _ javascript skills

Source: Internet
Author: User
I want to learn about the improvement of var pre-parsing and function declaration in javascript. I am not familiar with the knowledge of var pre-parsing and function declaration. I will share this article with you. 1. var variable pre-Compilation

The syntax of JavaScript is similar to that of C, Java, and C. If you have experience in C or Java programming, you should be familiar with the "declare first and then use" rules. If you use undeclared variables or functions, an error will be reported during the compilation phase. However, JavaScript can use variables and functions before they are declared. Next, let's take a closer look at the xuanjicang.

Let's take a look at a piece of code:

(function() { console.log(noSuchVariable);//ReferenceError: noSuchVariable is not defined})();

An error is immediately reported when running the above Code. However, this is exactly what we expect, because the noSuchVariable variable is not defined at all! Let's take a look at the following code:

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

First, the above Code is correct and there is no problem. However, why not report an error? What is the declaredLater variable defined after the call statement? Why is undefined output?

This is actually a ghost of the JavaScript parser. The parser puts all the variables and functions declared in the current scope at the beginning of the scope. However, only the declaration of variables is advanced to the beginning of the scope, and the assignment operation is kept in the original place. The above code is actually like this for the Parser:

(Function () {var declaredLater; // The declaration is advanced to the beginning of the scope! Console. log (declaredLater); // undefined declaredLater = "Now it's defined! "; // The assignment operation is still in place! Console. log (declaredLater); // "Now it's defined! "})();

This is why the above Code does not report exceptions! After variables and functions are "in advance", the declaredLater variable is put before calling the function. According to the definition of JavaScript syntax, variables that have been declared but not assigned a value will be automatically assigned an undefined value. Therefore, the value of the declaredLater variable printed for the first time is undefined. We will assign a value to the declaredLater variable later, the second printing of the variable will output Now it's defined !.

Let's look at an example:

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

In the above Code, we first declare a variable name. Our intention is to output the name variable defined globally when the name variable is printed for the first time, then define a local name variable in the function to overwrite the global variable, and output the local variable value. However, the output result for the first time is completely different from our expectation, because the local variables we define are "advanced" in their scope, that is, they become the following form:

Var name = "Baggins"; (function () {var name; // Note: The name variable is in advance! 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 a "quirks", we recommend that you put the variable declaration at the top of the scope so that you can always pay attention to it.

2. function declaration "advance"

The front side is about variables. Let's talk about functions.

There are two conditions for a function to be "advanced": function declaration and function value assignment to a variable, that is, a function expression.

First, let's start with the code:

isItHoisted();//"Yes!"function isItHoisted() {  console.log("Yes!");}

As shown above, the JavaScript interpreter allows you to use it before the function declaration. That is to say, the function declaration is not just a function name "in advance", but the definition of the entire function is also "in advance! Therefore, the above Code can be correctly executed.

Let's look at the second case: function expression form. Check the code first:

definitionHoisted();// "Definition hoisted!"definitionNotHoisted();// TypeError: undefined is not a functionfunction definitionHoisted() {  console.log("Definition hoisted!");}var definitionNotHoisted = function () {  console.log("Definition not hoisted!");};

We made a comparison, and the definitionHoisted function was properly executed, in line with the first type; the definitionNotHoisted variable was "advanced", but his value (that is, the function) it is not in advance. From this point of view, it is exactly the same as the variable "in advance", and because the default value of the variable "in advance" is undefined, therefore, the error "Type mismatch" is reported because undefined is not a function and cannot be called.

Summary
The above explanation can be summarized as follows:

The variable declaration is advanced to the top of the scope, and the assignment value is retained in the original place.
The entire function declaration is "in advance"
When a function expression is used, only the variable is "in advance" and the function is not "in advance"
3. Side effects of var

There is a small difference between implicit global variables and clearly defined global variables, that is, the ability to define variables through the delete operator.

Global variables created through var (created in programs other than functions) cannot be deleted.
Implicit global variables created without var (ignore whether or not they are created in the function) can be deleted.
This indicates that, technically, implicit global variables are not real global variables, but they are attributes of global objects. Attributes can be deleted using the delete operator, but variables cannot:

// Define three global variables var global_var = 1; global_novar = 2; // The opposite textbook (function () {global_fromfunc = 3; // The opposite textbook }()); // try to delete global_var; // falsedelete global_novar; // truedelete global_fromfunc; // true // test whether to delete typeof global_var; // "number" typeof global_novar; // "undefined" typeof global_fromfunc; // "undefined"

In ES5 strict mode, an error is thrown when undeclared variables (such as the two opposite textbooks in the previous code snippet) work.

4. Declare variables in the form of single var

Using a single var statement at the top of a function is a useful form. Its advantages include:

Provides a single place to find all the local variables required by the function
Prevent logical errors used before variables are defined
Less code (type, pass value, single line)
The single var format looks like the following:

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 and separate them with commas. It is good to initialize values at the same time like this. This prevents logical errors (the initial values of all uninitialized but declared variables are undefined) and increases code readability. After you see the code, you can know the general purpose of these variables based on the initialization value.

The above is the improvement of var pre-parsing and function declaration for javascript. I hope this will be helpful for your learning.

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.