What is a function
1. Substance and significance
- A function is really a method; Meaning is encapsulation
2. Application:
- Encapsulate the code that implements a function together, and then you just need to execute the function, and you don’t need to rewrite the code
3. Purpose:
- Reduce redundant code in pages, improve code reuse, “Low coupling, high cohesion”
Two, two important parts of the function
Mind mapping
1. Create functions
1). Grammar:
- Function Name (parameter){function body}
-2). Creation process:
- The first step:
- Create value:
- Create a heap of memory
- Store the code in the function body as a string in the heap
- 3. Put the heap address on the stack
- Create value:
- The second step:
- Create a variable
- Step 3:
- Associate variables with addresses
Note: just creating a function creates a heap of strings, and has no real effect
2. Execute the function
1). Grammar:
- Function name (argument)
– 2)
- Execute the created function (execute the code in the function body)
-3). Dependent conditions
- Stack memory
- Context for code execution
We know that the browser has already created the ECStack execution environment stack when the page loads, so we only need to create a new execution context when we execute the function.
-4). Execution Process:
Each time a function is executed, it is executed in the following order;
- The first step:
- Create a new execution context and compress it into stack memory for execution (push execution)
- The second step:
- In this context, there is also an AO (variable object) that stores variables created during the execution of the current context code
- These variables are private variables
- The value of a private variable cannot be used directly outside the context, except in the current context
- In this context, there is also an AO (variable object) that stores variables created during the execution of the current context code
- . We’re going to start with the basics, so we’re going to skip some of the detailed steps, and we’re going to get better and better;
- Step 3:
- Code execution
- Step 4:
- When all the code in the context has been executed, if the information in the context is not occupied by the outside world, it is executed out of the stack (freed) to reduce the space in the stack memory.
Legend of function operation mechanism:
Three, the form of parameters
Mind mapping
1, the parameter
- Definition:
- When creating a function, we do not know what data we need to process. We only know when the function is executed. At this point, we need to define the corresponding entry, which is called parameter in JS function.
- Function:
- “Used to store information passed in when a function is executed.”
- So parameters are variables
2, the arguments
- Definition:
- When the function is executed, the value passed in will be assigned to the parameter. The specific value passed in JS functions is called an argument.
- Function:
- “Arguments are the values that are passed.”
function sum(x, y) {
let total = x + y;
console.log(total);
}
sum(1= = =1 ? 'OK' : 'NO'); //=> We also need to pass the result of the ternary expression operation to the parameter as an argument
let age = 20;
sum(age); Sum (20) =>sum(20) =>sum(20) =>sum(20)
Copy the code
Parameters are the variables set when the function is created, and the arguments are the specific values passed to the parameters when the function is executed
Is involved in the correspondence of arguments
- 1. If the parameter is set and no value is passed, the default value of the parameter is
undefined
- 2. When a function has three arguments and only two parameters, no corresponding parameter is received for the third argument (but is passed to the function).
3, the arguments
- Definition:
- A collection of built-in arguments to a function
- Regardless of when we set the parameter, or whether we pass the argument,
arguments
There will always be (ES6
It’s not in the arrow functionarguments
) - Can only occur in a function body
- Form:
arguments
Is a collection of class arrays- Like an array, but not an array, and a collection of elements
HTMLCollection
similar
- Principle:
- Every argument passed in is logged according to the index (regardless of whether a parameter is defined).
arguments
Contains all the argument information passed inlength
Attribute represents the number of arguments passed
- Chestnut 🌰 : Sum of any number: no matter how many argument values are passed in, we can find the corresponding sum
//================= Sum of any number: we can find the corresponding sum no matter how many arguments we pass in
// There is a specific problem: it is no longer practical to receive summation numbers based on parameters, since we do not know how many values to pass, so we cannot determine how many parameters to define
function sum() {
// Loop ARGUMENTS add each argument (each argument passed in) to TOTAL to get the sum
let total = 0;
for (let i = 0; i < arguments.length; i++) {
// Convert all incoming argument information to numbers: exclude invalid numbers or strings
let item = Number(arguments[i]);
if (!isNaN(item)) {
// Significant digitstotal += item; }}console.log(total);
}
sum(); / / = > 0
sum(10); / / = > 10
sum(10.20); / / = > 30
sum(10.20.30.40); / / = > 100
sum(10.20.'AA'); //=>30 Filter out invalid numbers
sum(10.'20'); //=>30 If the string is a string, it cannot be a string concatenation but a mathematical addition
Copy the code
Residual operators in ES6
- Grammar:
. args
(args
For arbitrary variable name)
- Definition:
- Store all the arguments passed in as an array to
args
variable
- Store all the arguments passed in as an array to
- Use:
- If you do not want to collect all of the remaining parameters, you can combine the regular parameters with the remaining parameters.
- A general argument, gets the value of a parameter. And then the rest of the arguments
. args
Receive the remaining parameters.
- The above 🌰 is implemented with the remainder operator:
functionsum(... args) { // ... Args: The remaining operators in ES6 store the argument information passed in as arrays in args variableslet total = 0;
for (let i = 0; i < args.length; i++) {
let item = Number(args[i]);
if(! isNaN(item)) { total += item; } } console.log(total); } sum(10, 20, 30, 40);Copy the code
The differences between the remaining arguments and arguments objects
- 1, the remaining parameters contain only those arguments that have no corresponding parameters, and
arguments
The object contains all the arguments passed to the function. - 2,
arguments
Object is not a real array, and the remaining arguments are realArray
The instance
Return value
Mind mapping
- Definition:
- So, if the outside world wants to use some private information in the current context, the function needs to provide the corresponding exit for the outside world to use the information, and this exit is in
JS
The function is called the return valuereturn
“
- So, if the outside world wants to use some private information in the current context, the function needs to provide the corresponding exit for the outside world to use the information, and this exit is in
- Function:
- 1, based on
return
Expose the value of a variable for outside use- Create a variable outside to receive the value returned by the function execution (i.e
return
Subsequent values)
- Create a variable outside to receive the value returned by the function execution (i.e
- 2, tell the function body that the following code is not executing
- 1, based on
Return must be followed by a variable
- Such as:
- Console. log (sum) :
- This is the sum function itself;
- Sum = function
- console,log (sum());
- Is for the function to execute
- This output is the return value of the function
- If I didn’t write it in the function
return
, the default return value isundefined
- Console. log (sum) :
Fifth, the expression form of function
Mind mapping
1. Real-name functions
- It has a function name
2. Anonymous functions
- -1). Function expression
- To assign a function as a value to a variable
- event
document.body.onclick = function () { // This is the anonymous function }; let fn = function () { // also anonymous function fn represents this function similar to function fn }; Copy the code
- -2). Self-executing function
- The function is executed immediately after it is created
- When you create a function,
function
Enclosing a parenthesis or preceded by a special character is syntactic- (function (n) {… }) (arguments) :
- + function (n) {… } (arguments)
- -function (n) {… } (arguments)
- ~ function (n) {… } (arguments)
- ! Function (n) {… } (arguments)
3. Arrow function
I’m not going to go into details
- Grammar:
- let func = (x,y) => {… };
//============== arrow functions (the new way to create functions defined in ES6)
let func = (x, y) = > {
// x and y are form variables
// The body of the function is still inside the braces
};
func(10.20);
//=> Arrow functions simplify the way functions are written: if there is only one RETURN in the function body, you can omit braces and RETURN
let sum = (x, y) = > x + y;
function sum(x, y) {
return x + y;
}
function func(x) {
return function (y) {
returnx + y; }}let func = x= > y => x + y;
Copy the code