Home > Web Front-end > JS Tutorial > Detailed introduction to variable scope and variable promotion in javascript_javascript skills

Detailed introduction to variable scope and variable promotion in javascript_javascript skills

WBOY
Release: 2016-05-16 17:19:03
Original
1152 people have browsed it

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 scope is divided into local scope and global scope.

Local variables (scope at function level)
Unlike other object-oriented programming languages ​​​​(such as C, Java, etc.), JavaScript does not have block-level scope (surrounded by curly braces); when , JavaScript has function-level scope, that is to say, variables defined within a function can only be accessed within the function or by functions within the function (except for closures, which we will write a topic on in a few days).

An example of function-level scope:


Copy code The code is 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

has no block scope:


Copy code The code is as follows:

var name = "Richard";
// the blocks in this if statement do not create a local context for the name variable
if (name) {
name = "Jack"; // this name is the global name variable and it is being changed to "Jack" here
console.log (name); // Jack: still the global variable
}

// Here, the name variable is the same global name variable, but it was changed in the if statement
console.log (name); // Jack

// Don’t forget to use the var keyword
// If you declare a variable without using the var keyword, 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, 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 is always a local variable and it will not overwrite the global variable
console.log (name);
}
// local variable Priority is greater than global variables
//If a variable in the global scope is declared again in the local scope, then when calling this variable in the local scope, the variable declared in the local scope will be called first:
var name = "Paul";

function users () {
// Here, the name variable is 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 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).

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

Copy code The code is as follows:

// name and sex is not in any function
var myName = "zhou";
var sex = "male";

//They are all in the window object
console.log(window.myName); //paul
console.log('sex' in window); //true


If a variable is initialized/declared for the first time without using the var keyword, it will automatically be added to the global scope.

Copy code The code is as follows:

function showAge(){
//The var keyword is not used when 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

setTimeout The function is executed in the global scope

The function in setTimeout is in the global scope, so when the this keyword is used in the function, the this keyword points to the global object (Window):

Copy code The code is 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 the global scope, generally we declare as few global variables as possible.
Variable Hoisting
All variable declarations will be hoisted to the beginning of the function (if the variable is inside the function) or the beginning of the global scope (if the variable is a global variable). Let’s look at an example:

Copy code The code is as follows:

function showName () {
console.log ( "First Name: " name);
var name = "Ford";
console.log ("Last Name: " name);
}

showName ();
// First Name: undefined
// Last Name: Ford

// The reason undefined prints first is because the local variable name was hoisted to the top of the function
// Which means it is this local variable that get calls the first time.
// This is how the code is actually processed by the JavaScript engine:

function showName () {
var name; // name is hoisted (note that is undefined at this point, since the assignment happens below)
console.log ("First Name: " name); // First Name: undefined

name = "Ford"; / / name is assigned a value

// now name is Ford
console.log ("Last Name: " name); // Last Name: Ford
}

Function declaration will overwrite variable declaration
If there is a function declaration and a variable declaration (note: it is just a declaration, not assigned a value), and the variable name and function name are the same, then, They will all be prompted to the beginning of the outer scope, but the function has higher priority, so the value of the variable will be overwritten by the function.

Copy code The code is 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 this variable or function is assigned a value, then the other one will not be able to overwrite it:

Copy code The code is as follows:

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

function myName () {
console.log ("Rich") ;
}

console.log(typeof myName); // string

Last point, in strict mode, if you assign a value to a variable without declaring it first, an error will be reported!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template