This time I will bring you a detailed explanation of javascript, What are the precautions when using javascript, the following is a practical case, let’s take a look .
Closure, this name is so strange,
Let’s get back to the point, let’s talk about the variables of js functionScope
The following examples are all based on local variables
Accessing function external variables inside the function
demo1: var a = 100; function get() { console.log(a) } get(); // 运行结果:100
In the demo1 example, variable a is declared outside the function and can be called in the function get(). Call the get() function, The browser console will output 100, which is the value of a.
External access to variables declared within the function
demo2: function get() { var a = 100; } get(); console.log(a); //运行结果:ReferenceError: a is not defined
In the demo2 example, the variable a is declared in the function get(). After the function get() is executed, the variable a is called. In the control Station output: ReferenceError: a is not defined (a is not defined). It can be seen that variables declared within the function cannot be directly called outside the function.
Isn’t it possible to get the variables inside the function? Of course not. Closures come in handy at this time. Look at the following code:
function get() { var a = 100; return function () { return a; } } var b = get(); console.log(b); //运行结果: /* function () { return a; }*/ console.log(b()); // 运行结果:100
The function get() returns a function. This function returns the variable you want to get, and then you can do it outside the function. Through get()(), you can get the value of the variable inside the function.
The above is the detailed content of Detailed explanation of must-have packages for JavaScript. For more information, please follow other related articles on the PHP Chinese website!