Three ways to declare variables in JS
(1) Use variable steps: a. Declaration --> b. Assignment --> 3. Call
Correct usage:
<script type="text/javascript"> // Method 1: Declaration and assignment are not separated var correctUsage = "Method 1 of correct use of variables" ; alert(correctUsage); // The value corresponding to the variable can be popped up // Method 2: Separation of declaration and assignment var correctUsage2; correctUsage2 = "The second way to use variables correctly" ; alert(correctUsage2); </script>
Incorrect usage:
<script type="text/javascript"> var correctUsage; // Error 1: Use alert(correctUsage) without assignment; // underfined // Error 2: Concatenate string without assignment correctUsage += "Change value without assignment " ; alert(correctUsage); // undefined change value without assignment </script>
(2) The generation and death of variables
The var keyword has been used to declare the table as an example
2.1 Variables declared outside functions
Generated: Generated when js is loaded on the line where the variable is located
death: js code is loaded, variable dies
2.2 Variables declared inside functions
Premise: The function where the variable is located is called
Generated: Generated when js executes to the line where the variable is located
Die: End of line of execution of the function where the variable is located
Example:
Scenario 1: The function is only declared, not called
<script type="text/javascript"> function test(){ var aa = "test"; aa +="Only declare, but when the function is not called, will the function be executed?"; // Add content alert(aa); aa = "The variable of this function will not be executed!" ; alert(aa); } </script>
Description: The above 2 alerts will not be executed
Scenario 2: Declare and call the function
function test(){ var aa = "test"; aa +="Only declare, but when the function is not called, will the function be executed?"; // Add content alert(aa); aa = "The variable of this function will not be executed!" ; alert(aa); } test();
Note: The above two alerts will be executed
(3) Global variables and local variables
3.1 Global variables
The variable is declared outside the function and can be accessed anywhere
3.2 Local variables
The variable is declared in the function body, and the variable can only be accessed in the function body
(4) 3 ways and scope of declaring variables
4.1 Use var (most common)
Variables declared by var can be global (outside the function) or function-level (inside the function)
function test() { globalVar = "This is a global variable" ; var partialVar = "This is a local variable" ; } test(); alert(globalVar); //this is a global variable alert(partialVar); //Direct error
Note: When declaring variables inside a function, be sure to use the var command. If not, you actually declare a global variable
Scenario 1:
var varLocation = "declare and assign outside function" ; function test(){ varLocation = "Change the value inside the function" ; alert(varLocation); // Change the value inside the function } test(); alert(varLocation); // Change the value inside the function
Description: For a variable declared outside the function, after the value is changed inside the function, the value of the variable outside the function also changes.
Scenario two:
var varLocation = "declare and assign outside function" ; function test(){ var varLocation = "change value inside function" ; alert(varLocation); // Change the value inside the function } test(); alert(varLocation); // Change the value inside the function
Explanation: After declaring a variable with var outside the function, and then declaring it again with var inside the function and changing its value, the value of the variable outside the function will not change.
4.2 Using const
Const is used to modify constants. The defined variables cannot be modified and must be initialized. The declaration position is not limited (usually declared at the beginning of js), which is the same as the final keyword of java classes.
Example:
function test(){ const testConstant = "Test Constant" ; alert(testConstant); testConstant = "Change constant value" ; } test();
4.3 Using let
Variables declared by let are used in {}, and the scope of variables is limited to the block-level scope
Example: Use js to dynamically add a li object to ul and click on the first item to display the current click
window.onload = function (){ var ul = document.getElementById("ulList" ); for ( var i = 0 i <= 5; i++ ){ // Create a li object var li = document.createElement("li" ); // The content in the li tag is set to: Itemi li.appendChild(document.createTextNode("Item" + i)); // Declare a block-level variable j and assign i to j let j = i; // Bind the click event li.onclick = function (){ alert("Item" + i + "is clicked."); }; ul.appendClild(li); } }
Wrong way:
window.onload = function (){ var ul = document.getElementById("ulList" ); for ( var i = 0 i <= 5; i++ ){ // Create a li object var li = document.createElement("li" ); // The content in the li tag is set to: Iteri li.appendChild(document.createTextNode("Item" + i)); // Bind the click event li.onclick = function (){ alert("Item" + i + "is clicked."); }; ul.appendClild(li); } }
Result: Click on each li, and the prompt is "Item 6 is clicked."
Extension: How to achieve this effect using var? Closure
window.onload = function (){ var ul = document.getElementById("ulList" ); for ( var i = 0 i <= 5; i++ ){ // Create a li object var li = document.createElement("li" ); // The content in the li tag is set to: Iteri li.appendChild(document.createTextNode("Item" + i)); // Bind the click event li.onclick = ( function (i){ return function (){ alert("Item" + i + "is clicked."); }; })(i) // Closure // Splicing the LI object item into the UL tag body ul.appendClild(li); } }
Note: The closure method used has already passed the value of j to the corresponding click event when binding, so the same result can be achieved, but it is not recommended for program maintainability.
4.4 Items for declaring variables
4.4.1 The principle of the variable value declared by js: the principle of proximity;
4.4.2 js is a weakly typed language, different data types can be represented by the same variable name;
4.4.3 The variable declared inside the function will not affect the value of the variable with the same name outside the function.
Example:
var testVarValue = "Test proximity principle" ; <script type="text/javascript"> function test() { const testRepeatStatement = "Test assigning different types and different values to a variable" ; alert(testRepeatStatement); // Test assigns different types and different values to a variable } test(); </script>
(5) How to avoid global pollution?
Method: Closure
Example:
(function(){ // declare a JSON object var JsonObj = {}; // Define the attributes and attribute values of the object JsonObj.name = "Attributes of the object" ; JsonObj.method = function() { alert( "Test if this method can be called" ); return JsonObj.name; } // By operating the window object, the properties and methods of the object can be accessed externally window.GlobalObj = JsonObj; })(); // call the method of the object and accept the return value var name = GlobalObj.method(); // Get the return value name alert(name); // Object properties // only get the method but don't call it var method = GlobalObj.method; // Get the method1() method of the object GlobalObj2 alert(method); // function (){ // alert("Test if this method can be called"); // return JsonObj.name; //} // calls the received method, but does not accept the return value method();
The advantages and disadvantages of closures are explained:
Advantages: Design private methods and variables to protect the safety of variables within functions;
Disadvantages: Closures have a very serious problem, that is, the problem of memory waste. This memory waste is not only because it is resident in memory, but more importantly, improper use of closures will result in invalid memory.