Phenomenon:
1. In JavaScript, the declaration of variables and functions will be promoted to the top execution.
2. The improvement of function is higher than the improvement of variables.
3. If an external variable with the same name is declared inside the function with var, the function will no longer look upward.
4. Anonymous functions will not be promoted.
5. Functions in different <script> blocks do not affect each other.
example:
Function declaration promotion higher than variable declaration
//Declare the variable a and function avar a; function a() {} alert(typeof a); //The "function" is displayed, which preliminarily proves that the priority of function is higher than var. //Declare the function first and then declare the variable, proving that the above example does not function overwrite the variable function a() {}var a; alert(typeof a); //The display is still "function", not "undefined", that is, the priority of the function is higher than var. //Declare the variable and assign the value function a() {}var a = 1;alert(typeof a); //number, it is not a function at this time. //Note: "var a=1" is equivalent to "var a;a=1", that is, declare first and then assign a value. "a=1" is equivalent to reassigning a, which is naturally number!The function uses var to define the same variable as the outside, and the function will no longer look for external variables upwards.
var value = 'hello';function show() { alert(value); if (!value) { var value = 'function'; } alert(value);}show() //The function is called here and pops up "undefined", "function"//The above example is equivalent to var value = 'hello';function show() { var value; //Note this line alert(value); if (!value) { value = 'function'; //This line removes var } alert(value);}show()//1. If the value internally defined in the show in the above column does not use var, an external variable will be used, and "hello" will pop up, "hello". //2. If the value is not defined inside the function, the value value outside can also be obtained.Anonymous functions will not improve upwards
getName()var getName = function () { alert('closule')}function getName() { alert('function')}getName()//The above code is equivalent to function getName() { //The function is raised up alert('function')}getName()var getName = function () { alert('closule')}getName()//The code execution pops up "function" and "closule"Functions in different <script> blocks do not affect each other
<script> getName() var getName = function () { alert('closule') }<script><script> function getName() { alert('function') }<script>//Code execution error: TypeError: getName is not a function//Because the getName() function in the first <script> block is not defined, the anonymous function will not be promoted upwardsThe above brief discussion on the improvement of variables and function declarations in JavaScript is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.