Learn from me about javascript's var preparsing and function declaration improvement

  • 2020-11-03 22:00:15
  • OfStack

1, var variable precompilation

The JavaScript syntax is similar to C, Java, and C#, and is collectively referred to as the C class syntax. Students with C or Java programming experience should be familiar with the "declare first, use later" rule. If you use undeclared variables or functions, errors will be reported at compile time. However, JavaScript is able to use variables and functions before they are declared. Let's take a closer look at 1 of the mysteries.

Let's start with a snippet of code:


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

Running the above code immediately causes an error, but that's exactly what we'd expect, since the noSuchVariable variable isn't defined at all! Consider 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 without any problems. But, why not report an error? The declaredLater variable is defined after the call statement, right? Why is undefined the output?

This is actually a trick of the JavaScript parser, which places all variables and functions declared in the current scope at the beginning of the scope, but only the variable declaration is advanced to the beginning of the scope, leaving the assignment in place. The above code actually looks like this for the parser:


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

This is why the above code does not report exceptions! Variables and functions, after "be" ahead of declaredLater variables actually was on the front of the called function, based on the definition of JavaScript grammar, it is not declared to the assignment of variables will be automatically assigned to undefined, so, the first printed declaredLater the value of the variable is undefined, behind we declaredLater variables for the assignment operation, so the second and print output variables will be Now it 's defined! .

Here's another 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 identified one variable, name. Our intention was to print the name variable for the first time to output the globally defined name variable, then define a local name variable in the function to override the global variable, and finally output the value of the local variable. However, the output result of the first time is completely different from our expectation. The reason is that the local variable defined by us is "advanced" in its scope, that is, it becomes the following form:


var name = "Baggins";
(function () {
 var name; // Note: name  The variable has been moved up! 
 console.log("Original name was " + name);// "Original name was undefined"
 name = "Underhill";
 console.log("New name is " + name);//"New name is Underhill"
})();

Because of this quirk of JavaScript, it is recommended that you put variable declarations at the top of the scope so that you are always aware of them.

2. Function declaration "advanced"

We talked about variables, and then we talked about functions.

The "advance" of a function can be divided into two cases, one is a function declaration, and the other is a function assigned as a value to a variable, namely a function expression.

Let's start with the first case, the above code:


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

As shown above, the JavaScript interpreter allows you to use it before a function declaration, which means that not only is the function name "advanced," but the entire definition of the function is "advanced!" So the above code executes correctly.

Consider the second case: the functional form. Let's start with the 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 do a comparison, definitionHoisted function is executed no problem, in line with the first type; definitionNotHoisted variables "in advance", but his assignment (function) has not been in advance, in the 1 point, and what we speak in front of the variable "to be" ahead of time is 1 to completely, and, due to the default values of the variables of "be" in advance is undefined, so the mistakes belongs to "type mismatch", because undefined not function, of course not be invoked.

conclusion
The above explanation can be summarized as follows:

The declaration of a variable is advanced to the top of the scope and the assignment is left in place
The whole function declaration is "advanced"
In a function expression, only the variable is advanced, the function is not advanced.
3. Side effects of var

A small difference between implicit and explicitly defined global variables is the ability to leave variables undefined through the delete operator.

Global variables created through var (created in a program other than any function) cannot be deleted.
Implicit global variables created without var (regardless of whether they are created in a function or not) can be deleted.
This shows that, technically, implicit global variables are not really global variables, but they are properties of global objects. Attributes can be removed by the delete operator, while variables cannot:


//  define 3 Global variables 
var global_var = 1;
global_novar = 2;  //  Cautionary tale 
(function () {
 global_fromfunc = 3; //  Cautionary tale 
}());

//  Try to delete 
delete global_var;  // false
delete global_novar; // true
delete global_fromfunc; // true

//  Test for deletion 
typeof global_var;  // "number"
typeof global_novar; // "undefined"
typeof global_fromfunc; // "undefined"

In strict ES5 mode, undeclared variables (such as the two examples in the previous code snippet) will throw an error when working.

4. Declare variables in single var form

Using a single var statement at the top of a function is one of the more useful forms that has the advantage of:

Provides a single 1 place to find all local variables required by the function
Prevents logical errors used before a variable is defined
Less code (type, pass value, single line complete)
The single var form looks like this:


function func() {
 var a = 1,
  b = 2,
  sum = a + b,
  myobject = {},
  i,
  j;
 // function body...
}

You can declare multiple variables with one var statement, separated by commas. It's nice to initialize variables and values at the same time like this. This prevents logical errors (all uninitialized but declared variables start with undefined) and increases the readability of the code. After you see the code, you can know the general purpose of these variables based on the values initialized.

Above is the var for javascript pre-parsing and function declaration improvement learning content, I hope to help you learn.


Related articles: