A function is a reusable block of code that is driven by an event or executed when it is called.
JavaScript function syntax
The function is a code block wrapped in curly braces, and the keyword function is used before:
function functionname() { Here is the code to be executed }
When this function is called, the code inside the function is executed.
Functions can be called directly when an event occurs (such as when the user clicks a button) and can be called anywhere by JavaScript.
Tip: JavaScript is case sensitive. The keyword function must be lowercase and the function must be called in the same case as the function name.
1. The scope of the function
Scope refers to the scope of the existence of a variable. There are two scopes in JavaScript. One is the global scope, where variables always exist throughout the program, and the other is the function scope, where variables only exist inside the function body. The variable declared outside the function body is a global variable, which can also be read inside the function body.
var v = 1; function f(){ (v); } f();
The above is a global variable, which can also be used inside the function body.
function f(){ var v = 1; }
And this is a local variable that cannot be read outside the function body.
2. Closure
A closure is a function defined inside the function body.
function f() { var c = function (){}; }
In the appeal code, c is defined in the function body f, and c is the closure.
The characteristic of closure is that variables inside the function body can be read outside the function body.
function f() { var v = 1; var c = function (){ return v; }; return c; } var o = f(); o(); // 1
The above code shows that originally we had no way to read the internal variable v outside of function f. However, with the help of closure c, this variable can be read.
Closures can not only read internal variables of the function, but also make the internal variables remember the operation results of the last call.
function f(b) { return function () { return b++; } } var b= f(5); b() // 5 b() // 6 b() // 7
The b variable inside the function is calculated based on the value of the last call.
The above is the full description of the functions (II) in JavaScript introduced to you by the editor. I hope you like it.