Variable scopes and variable improvements in javascript

Source: Internet
Author: User
In javascript, it is very necessary to understand the scope of variables and improve variables. It seems simple, but it is not what you think. You need to understand some important details. The scope of a variable indicates the context of the variable. It specifies in javascript that it is necessary to understand the scope of the variable and to improve the variable. It seems simple, but it is not what you think. You need to understand some important details. Variable scope "The scope of a variable indicates the context of the variable. It specifies which variables you can access and whether you have the permission to access a variable ." Variable scopes are divided into local scopes and global scopes. Unlike the programming languages (such as C ++ and Java) of other opposite objects, local variables (in function-level scopes) do not have block-level scopes (surrounded by curly brackets ); when Yes, javascript has a function-level scope. That is to say, variables defined in a function can only be accessed within the function or within the function (except for closures, we will write another topic in a few days ). An example of function-level scope: 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-level scope: var name = "Richard "; // the blocks in this if statement do not create a local context for the name variableif (name) {name = "Jack"; // this name is the global name variabl E 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 statementconsole. log (name); // Jack do not forget to use the var keyword. If the var keyword is not used when declaring a variable, this variable will be a global variable! // If you don't declare your local variables with the var keyword, they are part of the global scopevar 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 variableshowOrdinaryPersonName (); // Johnny Evers // The global variable is now Johnny Evers, not the celebrity name anymoreshowCelebrityName (); // Johnny Evers // The solution is to declare your local variable with the var keywordfunction showOrdinaryPersonName () {var name = "Johnny Evers "; // Now name is always a local variable and it will not overwrite the global variable console. log (name);} the priority of a local variable is greater than that of a global variable. If this variable is declared again in the local scope, when this variable is called in the local scope, the variable declared in the local scope is preferentially called: var name = "Paul"; function users () {// Here, the name variable is local and it takes precedence over the same name variable in the global scopevar name = "Jack "; // The search for name starts right here inside the function before it attempts to look outside the function in the global scopeconsole. log (name) ;}users (); // Jack global variables all variables declared outside the function are global Domain. In the browser environment, this global scope is our Window object (or the entire HTML document ). Every variable declared or defined outside the function is a global object, so this variable can be used anywhere, for example: // name and sex is not in any functionvar myName = "zhou"; var sex = "male"; // they are all in the console of the window object. log (window. myName); // paulconsole. log ('sex' in window); // true if the var keyword is not used during the first initialization/declaration of a variable, it is automatically added to the global scope. Function showAge () {// age does not use the var keyword during initialization, so it is a global variable age = 20; console. log (age) ;}showage (); // 20console. log (age); // because age is a global variable, the output function in 20setTimeout is the setTimeout Function executed in the global scope, when this keyword is used in a function, this keyword points to a global object (Window): 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 to avoid global scope pollution, we should declare as few global variables as possible. Variable Hoisting, so the declaration of variables will be promoted to the beginning of the function (if this Variable is in this function) or the beginning of the global scope (if this Variable is a global Variable ). Let's take an example: 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 callthe first time. // This is how the code is actually proce Ssed 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 Fordconsole. log ("Last Name:" + name); // The Last Name: Ford} function declaration overwrites the variable declaration. If a function declaration and a variable declaration exist (Note: it is only a declaration, and the variable names are the same as the function names. It indicates the beginning of the external scope. However, the function has a higher priority, so the variable value will be overwritten by the function. // Both the variable and the function are named myNamevar myName; functions myName () {console. log ("Rich");} // The function declaration overrides the variable nameconsole. log (typeof myName); // function however, if this variable or function is assigned a value, the other variable cannot overwrite it: // But in this example, the variable assignment overrides the function declarationvar myName = "Richard"; // This is the variable assignment (initialization) tha T overrides the function declaration. function myName () {console. log ("Rich");} console. log (typeof myName); // the last point of string. In strict mode, if the variable is not declared first, an error is returned if the variable is assigned a value!

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.