A function is an event-driven or reusable block of code that executes when it is called.
JavaScript function syntax
A function is a block of code wrapped in curly braces, preceded by the keyword function:
function functionname() { 这里是要执行的代码 }
When this function is called, the code within the function will be executed.
Functions can be called directly when an event occurs (such as when the user clicks a button) and can be called from anywhere by JavaScript.
Tip: JavaScript is case-sensitive. The keyword function must be lowercase, and the function must be called with the same case as the function name.
1. Scope of function
Scope refers to the scope in which a variable exists. There are two types of scopes in JavaScript, one is the global scope, where variables exist throughout the entire program, and the other is the function scope, where variables only exist inside the function body. Variables declared outside the function body are global variables, which can also be read inside the function body.
var v = 1; function f(){ console.log(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, which 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 the 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 outside the function f, we had no way to read the internal variable v. However, with the help of closure c, this variable can be read.
Closure can not only read the 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 previous call for each call.
The above is the entire description of functions in JavaScript (2) introduced by the editor to you. I hope you like it.