JavaScript exploration: var pre-parsing and side effects

Source: Internet
Author: User
There is a small difference between implicit global variables and clearly defined global variables, that is, using the delete operator to cause side effects of 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.

Additional reading

The topic list of this article is as follows:

  1. How should we understand the working principle of the JavaScript engine?
  2. JavaScript exploration: the importance of writing maintainable code
  3. JavaScript exploration: exercise caution when using global variables
  4. JavaScript exploration: var pre-parsing and side effects
  5. JavaScript exploration: for Loop (for Loops)
  6. JavaScript exploration: for-in loop (for-in Loops)
  7. Exploring JavaScript: Prototypes is too powerful
  8. JavaScript: eval () is the devil"
  9. JavaScript exploration: Using parseInt () for Numerical Conversion
  10. Exploring JavaScript: Basic coding specifications
  11. JavaScript exploration: function declaration and function expression
  12. JavaScript exploration: Name function expressions
  13. JavaScript: function name in the debugger
  14. JavaScript: JScript Bug
  15. JavaScript exploration: Memory Management of JScript
  16. Exploring JavaScript: SpiderMonkey's quirks
  17. JavaScript exploration: an alternative solution to naming function expressions
  18. JavaScript exploration: Object
  19. JavaScript exploration: Prototype chain
  20. JavaScript exploration: Constructor
  21. JavaScript probing: executable context Stack
  22. Execution context 1: Variable object and activity object
  23. Execution context 2: Scope chain Scope Chains
  24. Execution context 3: Closure Closures
  25. Execution context 4: This pointer
  26. Exploring JavaScript: Powerful prototype and prototype chain
  27. JavaScript Functions 1: function declaration
  28. JavaScript function 2: function expressions
  29. JavaScript function 3: function expressions in a group
  30. JavaScript function 4: function Constructor
  31. JavaScript variable object 1: VO Declaration
  32. JavaScript variable object 2: VO in different execution contexts
  33. JavaScript variable object 3: two stages of execution Context
  34. JavaScript variable object IV: Variables
  35. Property of the JavaScript variable object __parent _
  36. JavaScript scope chain 1: Scope chain Definition
  37. JavaScript scope chain 2: function Lifecycle
  38. JavaScript scope chain 3: Scope chain features
  39. JavaScript closure 1: Introduction to closures
  40. JavaScript closure 2: Implementation of closure
  41. JavaScript closure 3: Closure usage

This article is available at http://www.nowamagic.net/librarys/veda/detail/1623.

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.