Understanding JavaScript variable scopes is easier _ javascript skills

Source: Internet
Author: User
Variable scope is a topic involved in every programming language. It is also a required knowledge point for a programmer. It is helpful for you to deeply understand the variable scope and write stable programs. JavaScript itself, as a simple language, is just as dizzy with the variable scope issue, mainly because of the existence of JavaScript closures. This article does not explain in depth the scope of JavaScript variables (in fact, I am not able to talk about this topic more deeply), nor does it talk about the "closure" topic, this article only discusses the most practical knowledge of JavaScript scopes.

I. JavaScript SCOPE CLASSIFICATION
JavaScript has two scopes: Global (window) and function-level (function ). Function level (function) cannot be understood as "block level (braces {} level )".

Ii. Differentiate and define JavaScript global variables and local variables
1.1 variables defined on the outermost side of all functions are global variables that are defined using or without the var keyword. The global variable is actually parsed as an attribute of the window object, so we can access it using the "window. global variable name" method. We recommend that you directly use the variable name to access it without any need. The following example demonstrates the most common way to define global variables:

The Code is as follows:


Var msg1 = 'this is message 1 ';
Msg2 = 'this is message 2 ';
Alert (window. msg1); // This is message 1 access using the window keyword
Alert (window. msg2); // This is message 2
Alert (msg1); // This is message 1 indicates the access method with the window keyword omitted.
Alert (msg2); // This is message 2
Function otherFunction () {}// other function or object Declaration Code
Var otherObject = {};


1.2 global variables can be defined and obtained in the same function (local variable runtime environment. Instead of using the var keyword, you can easily obtain the global variable content in a local environment and directly reference it using the global variable name. Note: If the function defines a local variable with the same name as the global variable, the function uses its own local variable first. If you want to use a global variable with the same name, add the window prefix. Example:

The Code is as follows:


Var msg1 = 'this is message 1 ';
Var msg3 = 'this is message 3 ';
Function otherFunction ()
{
Msg2 = 'this is message 2'; // a global variable is defined instead of the var keyword.
Var msg3 = 'message 3 ';
Alert (msg1); // This is message 1 (the global variable defined outside can be accessed within the function, and the global variable can be obtained correctly after deep function nesting, this is one of the implementations of JavaScript closures)
Alert (msg3); // Message 3 (local variable msg3)
Alert (window. msg3); // This is message 3 (use the window prefix to access the global variable msg3 with the same name)
Alert (this. msg3); // This is message 3 (because otherFunction () is defined in a global environment, this of otherFunction () also points to window. msg3 is equal to this. msg3)
}
OtherFunction ();
// Msg1 defined outside the otherFunction and msg2 defined in it are still global variables
Alert (window. msg1); // This is message 1
Alert (window. msg2); // This is message 2


2.1 If the var keyword is used, the variable defined in the function body is a local variable, which can be used by all the statement blocks ({}) and subfunctions below. This variable can be accessed anywhere in the function, but it cannot be accessed "directly" outside the function (Closure allows indirect access, or proxy access, this knowledge point is not covered in this article ). Example:

The Code is as follows:


Function showMsg ()
{
If (true)
{
Var msg = 'this is message ';
}
Alert (msg); // This is message
}
ShowMsg ();
Alert (typeof (msg); // undefiend
// The variable msg defined in the if {} braces can also be accessed in the showMsg () outside the if clause, but cannot be accessed outside the showMsg () clause.


2.2 The variables of the parent function can be accessed by the quilt function, but the variables of the Child function cannot be accessed by the parent function. Obviously, this is consistent with the function-level scope we mentioned at the beginning. It seems like dad is better, and his son is mean. Example:

The Code is as follows:


Function showMsg ()
{
Var MsgA = 'message ';
This. setMsg = function (msg)
{
Var MsgB = 'message B ';
Alert (MsgA); // Message A (the sub-function setMsg () can access the local variable MsgA of the parent function showMsg)
}
Alert (MsgB); // MsgB undefined (the variable MsgB defined in its subfunction cannot be accessed in the parent function)
}
Var sm = new showMsg ();
Sm. setMsg ('message string ');


3. Notes and tips
1. To avoid confusion or overwriting of variables, do not add the var keyword to the definition of local variables. (if necessary, release the variable after it is used, that is, "variable name = null"). We recommend that you set all variables at the beginning of each function. Example:

The Code is as follows:


Var msg = 'message ';
Function showMsg ()
{
Var msg; // even if you accidentally use the same name as the global variable, you do not have to worry about overwriting the global variable with the same name.
Var;
Var B;
Var c;
For (a = 0; a <10; a ++ ){}
This. setMsg = function (){}
}


2. Use anonymous functions to reduce naming conflicts or variable pollution. The following two sections of Code actually implement the same function, while the first section of code can be written with the variable name you want to use in that anonymous function, you don't have to worry about overwriting variables defined by others or defined elsewhere.

The Code is as follows:


// Define an anonymous function and then drop the code into this anonymous function, which can effectively reduce name conflicts or variable pollution. This is a common practice of JS frameworks.
(Function ()
{
Var msg = 'this is message ';
Alert (msg );
})();
Document. write (msg); // msg is undefined (Other Methods outside the anonymous function cannot call the msg variable)
//-----------------------------
Var msg = 'this is message ';
Alert (msg );


3. We do not recommend using this instead of window to access global variables in functions that do not require instantiation. Generally, functions using the this keyword should be processed as JavaScript classes (I like to use "cls" as the class name prefix ). If the following functions are called only as common functions, this keyword should not appear, because this is usually used to operate a global variable. Example:

The Code is as follows:


Function clsMsg ()
{
This. msg = 'this is default message ';
This. showMsg = function ()
{
Alert (this. msg );
}
}
SMsg = new clsMsg ();
SMsg. msg = 'this is new message ';
SMsg. showMsg ();


Iv. Knowledge Point Guide
Understanding the following knowledge points will help you better understand the scope of JavaScript variables. This article will not be detailed for the time being. We will discuss it in a separate article, so stay tuned.
(1) Understanding JavaScript "pre-parsing"
(2) JavaScript Closure

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.