In-depth analysis of pre-resolution and side effects in JavaScriptvar

Source: Internet
Author: User
The side effects of var are slightly different 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 the side effects of true global variable 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.

Single var format

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

Help you remember declared global variables, so there are fewer global variables // zxx: Here I am a little dizzy...

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, for example, whether to use them as an object or as an integer.

You can also do some practical work during the Declaration, such as sum = a + B in the previous Code. Another example is when you use DOM (Document Object Model) when referencing, you can use a single var to specify DOM references together as local variables, as shown in the following code:

Function updateElement () {var el = document. getElementById ("result"), style = el. style; // use el and style to do something else ...}
Vars variable pre-resolution

In JavaScript, you can declare multiple var statements at any position of the function, and they serve as if they were declared at the top of the function, this behavior is called hoisting (mounting/top resolution/pre-resolution ). When you use a variable and then re-declare it in the function, logical errors may occur. For JavaScript, as long as your variable is in the same scope (the same function), it is declared, even when it is used before the var declaration. Let's look at the example below:

// Counterexample myname = "global"; // global variable function func () {alert (myname); // "undefined" var myname = "local"; alert (myname ); // "local"} func ();

In this example, you may think that the first alert is "global" and the second alert is "loacl ". This expectation is understandable, because at the first alert, myname was not declared. At this time, the function will naturally look at the global variable myname. However, this is not actually the case. The first alert will pop up "undefined" because myname is treated as a local variable of the function (although declared later), and all the variable declarations will be mounted to the top of the function. Therefore, to avoid such confusion, it is best to declare all the variables you want to use in advance.

The execution of the above code snippet may be like the following:

Myname = "global"; // global variablefunction func () {var myname; // equivalent to-> var myname = undefined; alert (myname ); // "undefined" myname = "local"; alert (myname); // "local"} func ();


For the sake of completeness, we will mention a little more complex at the execution layer. Code processing is divided into two stages. The first stage is variable, function declaration, and normal format parameter creation, which is a stage of parsing and entering the context. The second stage is code execution. function expressions and unqualified Identifiers (declared variables) are created. However, for practical purposes, we adopt the "hoisting" concept, which is not defined in the ECMAScript standard and is usually used to describe behavior.

Access Global Objects

In the browser, global objects can be accessed anywhere in the Code through the window attribute (unless you have done something out of the box, such as declaring a local variable named window ). However, in other environments, this convenient property may be called something else (or even unavailable in programs ). If you need to access a global object without a hardcoded window identifier, you can perform the following operations in the function scope at any level:

var global = (function () {   return this;}());


This method can obtain global objects at any time, because it is called as a function in the function (not constructed through new), this always points to the global object. In fact, this disease does not apply to the strict mode of ECMAScript 5. Therefore, in strict mode, you must take different forms. For example, if you are developing a JavaScript library, you can wrap your code in a real-time function, and then pass a reference pointing to this as a parameter of your real-time function from the global scope.

The above is an in-depth analysis of the pre-resolution and side effects in JavaScriptvar. For more information, see other related articles in the first PHP community!

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.