Variable scope and variable elevation in javascript detail _javascript tips

Source: Internet
Author: User
Tags variable scope


Variable scope
"The scope of a variable represents the context in which the variable exists. It specifies which variables you can access and whether you have permission to access a variable. ”



Variable scopes are divided into local scope and global scope.



Local variables (scoped to function level)
Unlike other programming languages (such as C++,java, etc.), JavaScript does not have a block-level scope (surrounded by curly braces), and when it does, JavaScript has a function-level scope, which means that Variables defined within a function can only be accessed within a function or within the function (except closures, which we'll write in a few days).



An example of a function-level scope:





 code as follows:

var name = "Richard";

function ShowName () {
var name = "Jack"; local variable; Only accessible in this showname function
Console.log (name); Jack
}
Console.log (name); Richard:the global variable







No block-level scope:





 code as follows:

var name = "Richard";
The blocks in this if statement don't create a local context for the name variable
if (name) {
Name = "Jack"; This name is the global name variable and it are being changed to "Jack"
Console.log (name); Jack:still the global variable
}

Here, the name variable is the same global name variable, but it being changed in the IF statement
Console.log (name); Jack




Don't forget to use the var keyword
If the var keyword is not used when declaring a variable, then the variable will be a global variable!
If you don ' t declare your local variables with the VAR keyword, they are part of the global scope
var name = "Michael Jackson";

function Showcelebrityname () {
Console.log (name);
}

function Showordinarypersonname () {
Name = "Johnny Evers";
Console.log (name);
}
Showcelebrityname (); Michael Jackson

Name is not a local variable, it simply changes the global name variable
Showordinarypersonname (); Johnny Evers

The global variable is now Johnny Evers and not the celebrity name anymore
Showcelebrityname (); Johnny Evers

The solution is to declare your local variable with the VAR keyword
function Showordinarypersonname () {
var name = "Johnny Evers"; Now name are always a local variable and it would not overwrite the global variable
Console.log (name);
}
Local variable priority greater than global variable
If the variable in the global scope is declared again in the local scope, the variable declared in the local scope is invoked preferentially when called in the local scope:
var name = "Paul";

function users () {
Here, the name variable are local and it takes precedence over the same name variable in the global scope
var name = "Jack";

The search for name starts right here inside the function before it attempts to look at outside the function in the global Scope
Console.log (name);
}

Users (); Jack








Global variables
All variables declared outside the function are in the global scope. In a browser environment, this global scope is our Window object (or the entire HTML document).



Each variable declared or defined outside the function is a global object, so the variable can be used anywhere, for example:





 code as follows:

Name and sex is isn't in any function
var myname = "Zhou";
var sex = "male";

They're all in window objects.
Console.log (Window.myname); Paul
Console.log (' Sex ' in window); True




If a variable does not use the var keyword the first time it is initialized/declared, then he automatically joins the global scope.







 code as follows:

function Showage () {
The VAR keyword is not used when the age is initialized, so it is a global variable
Age = 20;
Console.log (age);
}

Showage (); 20
Console.log (age); Because age is a global variable, the output here is also 20

Functions in SetTimeout are performed in the global scope





The functions in settimeout are in the global scope, so when the This keyword is used in a function, the This keyword points to a global object (Window):





 code as follows:

var Value1 = 200;
var Value2 = 20;
var myobj = {
Value1:10,
Value2:1,

Caleculatedit:function () {
settimeout (function () {
Console.log (this. Value1 * this. Value2);
}, 1000);
}
}

Myobj.caleculatedit (); 4000







In order to avoid contamination of global scope, we generally declare global variables as little as possible.
Variable elevation (Variable hoisting)
So the variable declaration is elevated to the beginning of the function (if the variable is inside the function) or to the beginning of the global scope (if the variable is a global variable). Let's take a look at an example:





 code as follows:

function ShowName () {
Console.log ("Name:" + name);
var name = "Ford";
Console.log ("Last Name:" + name);
}

ShowName ();
The name:undefined
Last Name:ford

The reason undefined prints is because the local variable name being hoisted to the top of the function
Which means it is this local variable the ' get calls '.
This are how the code are actually processed by the JavaScript engine:

function ShowName () {
var name; The name is hoisted (the "is" undefined at this point, since the assignment happens below)
Console.log ("Name:" + name); The name:undefined

Name = "Ford"; Name is assigned a value

Now name is Ford
Console.log ("Last Name:" + name); Last Name:ford
}







A function declaration overrides a variable declaration
If there are function declarations and variable declarations (note: is simply a declaration, has not been assigned, and the variable name is the same as the function name, then they are all prompted to the beginning of the external scope, but the function is higher precedence, so the value of the variable will be overwritten by the function.





 code as follows:

Both the variable and the function are named MyName
var myname;?
function MyName () {
Console.log ("Rich");
}

The function declaration overrides the variable name
Console.log (typeof myname); function







However, if the variable or function is assigned, the other one will not be able to overwrite it:





 code as follows:

But in this example, the variable assignment overrides the function declaration
var myname = "Richard"; This is the variable assignment (initialization) overrides the function declaration.

function MyName () {
Console.log ("Rich");
}

Console.log (typeof myname); String







Finally, in strict mode, if you do not first declare the variable to assign a value to the variable will be an error!


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.