Principle: The declaration of functions and variables will be promoted to the top of the function.
Result: Both variables and functions support trial first and then declaration
Case:
//变量提升x = 5; // 变量 x 设置为 5alert(x);var x; // 声明 x//函数提升print(5); //调用函数function print(y) { //声明函数 return y * y;}
Principle : Nest another function within the function (the other function is a closure)
Result:
There is no static variable in js, you can Local variables declared within a function are used as local variables
How to ensure that local variables are only called once? You can use variable assignment, that is, the outermost layer is called for the first time. Function, all subsequent calls to closures
can prevent other functions from modifying them (other functions can modify global variables at will)
Case:
function count() { var counter = 0; return function () {return counter += 1;}} var add= count();add(); add();//值为二
Related recommendations:
Detailed example code of how to determine the existence of functions and variables in JavaScript
Summary of basic JavaScript knowledge (10) Closures and immediate execution functions
The above is the detailed content of Explanation of promotion and closure of js functions and variables. For more information, please follow other related articles on the PHP Chinese website!