Understanding JavaScript Variable scopes more easily _javascript tips

Source: Internet
Author: User
Tags variable scope
JavaScript itself, as a simple language, makes many people dizzy as much as its variable scope problem, mainly because of the existence of JavaScript closures. This article is not going to delve into the scope of JavaScript variables (in fact, I also do not have the ability to talk about this topic more in-depth), also do not speak "closure" topic, this article only discusses the most practical JavaScript scope knowledge points.

One, JavaScript scope classification
JavaScript has two scopes: global (window), function level (function). The function level (function) is not understood as "block level (curly brace {} level)".

Ii. distinguishing and defining JavaScript global variables and local variables
1.1 Define variables that are the outermost of all functions and that are defined using or not using the VAR keyword are global variables. The global variable is actually parsed into a property of the Window object, so we can access it as a "window. Global variable name", recommending that the variable name be accessed directly, if not necessary. The following example illustrates the most common way to define a global variable:
Copy Code code as follows:

var msg1= ' This are message 1 ';
Msg2= ' This are message 2 ';
alert (WINDOW.MSG1); This are message 1 accessed using the Window keyword
alert (WINDOW.MSG2); This is message 2
alert (MSG1); This is message 1 omits access to the window keyword
alert (MSG2); This is message 2
function Otherfunction () {}//other functions or object declaration code
var otherobject={};

1.2 You can define and get global variables within a function (local variable run-time environment). The definition method is to not use the VAR keyword, and in the local environment can easily get the global variable content, directly using the global variable name reference. Note that if you define a local variable with the same name as a global variable, then the function body will use its own local variables, and if you want to use a global variable of the same name at this point, add the window prefix. Examples are as follows:
Copy Code code as follows:

var msg1= ' This are message 1 ';
var msg3= ' This are message 3 ';
function Otherfunction ()
{
Msg2= ' This are message 2 '; Do not use the var keyword, but also define a global variable
var msg3= ' message 3 ';
alert (MSG1); This is message 1 (within the function, of course, you can access the global variable that is defined outside, and the deeper function nesting can correctly get to this global variable, which is one embodiment of JavaScript closures)
alert (MSG3); Message 3 (local variable MSG3)
alert (WINDOW.MSG3); This is message 3 (Use the window prefix to access global variables with the same name MSG3)
alert (THIS.MSG3); This is message 3 (because Otherfunction () is defined in a global environment, at which point Otherfunction () also points to window, and all you see is window. MSG3 is equal to this. Msg3.)
}
Otherfunction ();
The MSG1 defined outside the Otherfunction function and the msg2 inside the definition are still global variables
alert (WINDOW.MSG1); This is message 1
alert (WINDOW.MSG2); This is message 2

2.1 using the var keyword, the variable defined in the function body is a local variable that can be used by all of the statement blocks ({}) and child functions below it. This variable can be accessed anywhere in this function, but it cannot be accessed "directly" outside of the function (closures allow for indirect access, or proxy access, which is not covered in this article). Examples are as follows:
Copy Code code as follows:

function ShowMsg ()
{
if (true)
{
var msg= ' this are message ';
}
Alert (msg); This are message
}
ShowMsg ();
Alert (typeof (MSG)); Undefiend
The variable msg defined here within the IF {} braces can also be accessed within the if outside ShowMsg (), but is inaccessible outside showmsg ()

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, which is obviously consistent with the function-level scope we started with. It looks like Dad is a little bit more generous, son. Examples are as follows:
Copy Code code as follows:

function ShowMsg ()
{
var msga= ' message A ';
This.setmsg=function (msg)
{
var msgb= ' message B ';
alert (MSGA); Message A (a child function setmsg () can access the local variable MSGA of the parent function showmsg ())
}
alert (MSGB); MSGB not defined (variable MSGB defined in its child functions cannot be accessed in the parent function)
}
var sm=new showmsg ();
Sm.setmsg (' message string ');

Iii. several places to be noted and the skills to use
1, in order to avoid the variable confusion or be covered, the definition of local variables must not forget to add the var keyword (when necessary, we want to use the variable after the active release of it, that is, "variable name =null"), while it is recommended that all the variables set in the first position in each function body Examples are as follows:
Copy Code code as follows:

var msg= ' message ';
function ShowMsg ()
{
var msg; Here, even if you accidentally use the same variable name as a global variable, you don't have to worry about overwriting a global variable with the same name
var A;
var b;
var C;
for (a=0;a<10;a++) {}
This.setmsg=function () {}
}

2, use anonymous function skillfully, reduce the naming conflict or variable pollution. The following two snippets of code actually implement the same functionality, and the first code can be used to boldly use the variable name you want to use in that anonymous function, without worrying about the variables that you define, or those you define elsewhere.
Copy Code code as follows:

Defining an anonymous function, and then dropping the code into this anonymous function, can effectively reduce the naming conflict or variable pollution, which is the common JS framework approach
(Function ()
{
var msg= ' this are message ';
Alert (msg);
})();
document.write (msg); MSG not defined (other methods outside the anonymous function cannot call msg this variable)
//-----------------------------
var msg= ' this are message ';
Alert (msg);

3. It is not recommended to use this instead of window to access global variables in functions that need not be instantiated. Generally, functions that use the This keyword should be treated as JavaScript classes (I prefer to prefix the "CLS" with the class name). The following function should not appear this keyword if it is called only as a normal function, because it is usually to manipulate a global variable. Example:
Copy Code code as follows:

function clsmsg ()
{
This.msg= ' This are default message ';
This.showmsg=function ()
{
alert (this.msg);
}
}
Smsg=new clsmsg ();
Smsg.msg= ' This is the new message ';
Smsg.showmsg ();

Four, relevant knowledge point guidance
Understand the following relevant knowledge points to help you better understand JavaScript variable scope, this article is not detailed, and then will be in a separate space, please pay attention.
(1) Understanding JavaScript "pre-resolution"
(2) JavaScript closures

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.