Js variables and their scopes

Source: Internet
Author: User
Tags define local variable scope

I. Variable type
Javascript is different from Java and C. It is a non-type, weak detection language. Its definition of variables does not need to declare the variable type. We only need to assign values to the same variable by assigning values to various types of data. For example:
Copy codeThe Code is as follows:
I = 100; // Number type
I = "variable"; // String type
I = {x: 4}; // Object type
I = [1, 2, 3]; // Array type

Although this feature of JS makes our encoding more flexible, it also brings about a disadvantage, which is not conducive to Debug. The weak detection of the compiler makes us quite painful to maintain lengthy code.
2. Variable Declaration
In JS, variable declarations are divided into explicit and implicit declarations.
Var I = 100; // explicitly declare
I = 100; // implicit statement
In a function, variables explicitly declared using the var keyword are used as local variables without the var keyword. global variables are declared using direct value assignment.
When we access an unspecified variable, JS reports an error. When we assign a value to a variable without declaration, JS will not report an error. On the contrary, it will think that we need to implicitly declare a global variable, which is 1.1 important.
3. Global and local variables
When the JS parser is executed, a global object is constructed in the execution environment. The Global attribute we define is read as the attribute of the object, in the top-level code, we can use the this keyword and the window object to access it. The local variables in the function body only exist in the called objects generated during function execution, and the local variables are destroyed immediately after the function is executed. Therefore, in program design, we need to consider how to reasonably declare variables, which not only reduces unnecessary memory overhead, at the same time, it can avoid repeated variable definitions and overwrite the debugging troubles caused by previously defined variables.
Iv. variable scope
The scope of variables in any programming language is a key detail. The scope of variables in JS is more free than that in JAVA and C. A major feature is that JS variables do not have block-level scopes and the variables in functions are valid throughout the function, run the following code:
Copy codeThe Code is as follows:
<Script language = "JavaScript" type = "text/javascript">
// Define an output function
Function outPut (s ){
Document. writeln (s)
}
// Global variable
Var I = 0;
// Define external functions
Function outer (){
// Access global variables
OutPut (I); // 0
// Define a class function
Function inner (){
// Define local variables
Var I = 1;
// I = 1; if implicit declaration is used, the global variable I is overwritten.
OutPut (I); // 1
}
Inner ();
OutPut (I); // 0
}
Outer ();
</SCRIPT>

The output result is 0 1 0. From the above, it can be proved that if Javascript declares a variable in the function body with var, this variable is valid only in the function body, and when the function stops running, local variables can be destroyed.
Due to the above JS features, there is another key issue to be noted. I have been using ActionScript for a long time. Although it and JS are both based on The ECMA standard, they are slightly different here. For example, the following code:
Copy codeThe Code is as follows:
<Script language = "JavaScript" type = "text/javascript">
// Define an output function
Function outPut (s ){
Document. writeln (s)
}
// Global variable
Var I = 0;
// Define external functions
Function outer (){
// Access global variables
OutPut (I); // 0
// Define a class function
Function inner (){
OutPut (I); // undefiend
Var I = 1;
OutPut (I); // 1
}
Inner ();
OutPut (I); // 0
}
Outer ();
</SCRIPT>

You may think that the output result is 0 0 1 0. In fact, this is true in AS, while in JS, the input is 0 undefined 1 0. Why? We just mentioned that the local variables declared in the JS function body are valid in the entire function, so var I = 1 in the above Code; they are valid in the inner function, in fact, the explicitly declared variable I has already been compiled into the calling object at the time of pre-compilation, unlike the implicit declaration variable that is defined as a global variable only during interpretation, only when outPut (I) is called, the variable has not been initialized. At this time, the local variable I is a non-assigned variable, rather than an undefined variable, so the undefined is outPut. The above code is equivalent to the following code:
Copy codeThe Code is as follows:
Function inner (){
Var I; // defined but not assigned a value
OutPut (I); // undefiend
I = 1;
OutPut (I); // 1
}

To avoid this type of problem, it is strongly recommended to make a function declaration in the beginning of the function.
5. Basic and reference types
Unlike JAVA and C, JS does not need to declare the storage space of variables when declaring variables. The data stored in the variable can be divided into two types: basic type and reference type. Values, Boolean values, null, and undefined belong to the basic type, and objects, arrays, and functions belong to the reference type.
The basic type has a fixed memory size in the memory. For example, the numeric type occupies eight bytes in the memory, and the Boolean value occupies only one byte. For referenced data, they can have any length, so their memory size is not fixed. Therefore, the variable is actually a reference to the data, usually the memory address or pointer, we can find this data through them.
The usage of the reference type and basic type is also different:
Copy codeThe Code is as follows:
<Script language = "JavaScript" type = "text/javascript">
// Define an output function
Function outPut (s ){
Document. writeln (s)
}
Var a = 3;
Var B =;
OutPut (B );
// 3
A = 4;
OutPut ();
// 4
OutPut (B );
// 3
</SCRIPT>

When assigning values to basic type B, a memory space is actually opened up. Therefore, changing the value of variable a has no effect on variable B.
Copy codeThe Code is as follows:
<Script language = "JavaScript" type = "text/javascript">
// Define an output function
Function outPut (s ){
Document. writeln (s)
}
Var a_array = [1, 2, 3];
Var B _array = a_array;
OutPut (B _array); // 1, 2, 3
A_array [3] = 4;
OutPut (B _array); // 1, 2, 3, 4
</SCRIPT>

The above is a value assignment to variables of the reference type. In fact, they pass a reference to the memory address. Therefore, the access to a_array and B _array is actually the same block of memory operated. If you want to re-allocate the memory space to store the referenced variables, you need to use the clone method or custom method to copy the data of the referenced variables.

JS variable scope
Copy codeThe Code is as follows:
<Script language = "javascript" type = "text/javascript">
Var a = "change ";
Function fun (){
Alert (a); // output undefined
Var a = "changed ";
Alert (a); // The output is changed.
}
Alert (a); // output change
Fun ();
</Script>

Var defines a variable in the scope. Before the first output of a, JS has assigned a value to change in the pre-compilation analysis. Therefore, it outputs change for the first time. When fun () is called () during function execution, JS creates a new scope. Before outputting a, the value of all var variables initialized is undefined. Therefore, the first output in fun () is undefined, the second output has assigned a value to a, so a new value is output. Two a variables are different from the other two variables in the function, for example:
Copy codeThe Code is as follows:
<Script language = "javascript" type = "text/javascript">
Var B;
Function fun (){
B = "change ";
}
Alert (B); // output undefined
</Script>

Variable B has been defined outside the function. In the function, value B is assigned, but undefined is output.

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.