A trip to the Empire??
content
address
Summary of JavaScript Foundation (I)??
https://blog.csdn.net/Augenstern_QXL/article/details/119249534
Function and scope of JavaScript Foundation (2)??
https://blog.csdn.net/Augenstern_QXL/article/details/119250991
JavaScript based objects and built-in objects (3)??
https://blog.csdn.net/Augenstern_QXL/article/details/119250137
Advanced DOM technology of JavaScript (4)??
https://blog.csdn.net/Augenstern_QXL/article/details/115416921
Advanced BOM technology of JavaScript (5)??
https://blog.csdn.net/Augenstern_QXL/article/details/115406408
Object oriented (VI) improvement of JavaScript??
https://blog.csdn.net/Augenstern_QXL/article/details/115219073
JavaScript improved ES6(7)??
https://blog.csdn.net/Augenstern_QXL/article/details/115344398
1. Function??
Function: encapsulates a code block that can be repeatedly called and executed. Through this code block, a large amount of code can be reused.
1.1. Use of functions??
Functions can be used in two steps: declaring functions and calling functions
① Declare function??
//Declarative function function Function name(){ //Function body code }
- Function is the keyword that declares the function and must be lowercase
- Since functions are generally defined to implement a function, we usually name the function as a verb, such as getSum
② Call function??
//Call function Function name(); //Execute the function body code by calling the function name
- Don't forget to add parentheses when calling
- Pithy formula: functions are not called, and they are not executed by themselves
Note: declaring the function itself will not execute the code, and the function body code will be executed only when calling the function.
1.2 function encapsulation
- Function encapsulation is to encapsulate one or more functions through functions, and only provide a simple function interface
1.3. Function parameters??
1.3.1 formal and actual parameters??
When declaring a function, you can add some parameters in parentheses after the function name. These parameters are called formal parameters. When calling the function, you also need to pass corresponding parameters, which are called arguments.
parameter
explain
Formal parameter
The parameters passed in the formal parameter function definition are unknown at present
Argument
In fact, the parameters and arguments passed during function call are passed to formal parameters
Function of parameters: some values cannot be fixed inside the function. We can pass different values through parameters when calling the function
// Function declaration with arguments function Function name(Formal parameter 1, Formal parameter 2 , Formal parameter 3...) { // You can define as many parameters as you want, separated by commas // Function body } // Function call with parameters Function name(Argument 1, Argument 2, Argument 3...);
For example: use the function to find the sum of any two numbers
// Declarative function function getSum(num1,num2){ console.log(num1+num2) } // Call function getSum(1,3) //4 getSum(6,5) //11
-
When a function is called, the argument value is passed to the formal parameter
-
Formal parameters are simply understood as variables that do not need to be declared
-
Arguments separated by commas (,),
1.3.2. The number of formal and actual parameters does not match??
Number of parameters
explain
The number of arguments is equal to the number of formal parameters
Output correct results
The number of arguments is more than the number of formal parameters
Only get the number of formal parameters
The number of arguments is less than the number of formal parameters
Multiple formal parameters are defined as undefined and the result is NaN
function sum(num1, num2) { console.log(num1 + num2); } sum(100, 200); // 300, the number of formal and actual parameters is equal, and the correct result is output sum(100, 400, 500, 700); // 500, the number of arguments is more than the formal parameters, and only the number of formal parameters is obtained sum(200); // If the number of arguments is less than the formal parameter, the more formal parameter is defined as undefined and the result is NaN
Note: in JavaScript, the default value of formal parameter is undefined
1.3.3 summary??
- Functions can take parameters or no parameters
- When declaring a function, the formal parameter is in the parentheses of the function name, and the default value of the formal parameter is undefined
- When calling a function, the argument is in the parenthesis of the function name
- Multiple parameters are separated by commas
- The number of formal parameters can not match the number of actual parameters, but the result is unpredictable. We should try to match
1.4 return value of function??
1.4.1 return statement??
Sometimes we want the function to return the value to the caller, which can be achieved by using the return statement.
The syntax format of the return statement is as follows:
// Declarative function function Function name (){ ... return Value to return; } // Call function Function name(); // At this point, you can call the function to get the value after return in the function body
-
When using the return statement, the function stops executing and returns the specified value
-
If the function does not return, the returned value is undefined
//Declarative function
function sum(){
...
return 666;
}
//Call function
sum(); // At this point, the value of sum is equal to 666, because the return statement will return the value after itself to the caller
1.4.2 return termination function??
The code after the return statement is not executed
function add(num1,num2){ //Function body return num1 + num2; // Note: the code after return will not be executed alert('I won't be executed because there's something ahead return'); } var resNum = add(21,6); // Call the function, pass in two arguments, and receive the return value of the function through resNum alert(resNum); // 27
1.4.3 return value of return??
Return can only return one value. If multiple values are separated by commas, the last one shall prevail
function add(num1,num2){ //Function body return num1,num2; } var resNum = add(21,6); // Call the function, pass in two arguments, and receive the return value of the function through resNum alert(resNum); // 6
1.4.4 summary??
All functions have return values
- If there is a return, return the value after the return
- If there is no return, return undefined
1.4.5. Difference??
The difference between break, continue and return
- break: end the current loop body (e.g. for, while)
- Continue: jump out of this cycle and continue to execute the next cycle (such as for and while)
- Return: it can not only exit the loop, but also return the value in the return statement. At the same time, it can also end the code in the current function body
1.4.5 practice
1. Use the function to find the maximum value of any two numbers
function getMax(num1, num2) { return num1 > num2 ? num1 : num2; } console.log(getMax(1, 2)); console.log(getMax(11, 2));
2. Find the maximum value in the array [5,2,99101,67,77]
//Define a function to get the maximum number in the array function getMaxFromArr(numArray){ var maxNum = numArray[0]; for(var i = 0; i < numArray.length;i++){ if(numArray[i]>maxNum){ maxNum = numArray[i]; } } return maxNum; } var arrNum = [5,2,99,101,67,77]; var maxN = getMaxFromArr(arrNum); //This argument is an array alert('The maximum value is' + maxN);
3. Create a function to realize the addition, subtraction, multiplication and division between two numbers, and return the result
var a = parseFloat(prompt('Please enter the first number')); var b = parseFloat(prompt('Please enter the second number')); function count(a,b){ var arr = [a + b, a - b, a * b, a / b]; return arr; } var result = count(a,b); console.log(result)
1.5. Use of arguments??
When we are not sure how many parameters are passed, we can use arguments to get them. In JavaScript, arguments is actually a built-in object of the current function. All functions have a built-in arguments object, which stores all the arguments passed.
-
Arguments stores the passed arguments
-
arguments is displayed as a pseudo array, so it can be traversed. Pseudo arrays have the following characteristics
① : has the length attribute
② : store data by index
③ : push, pop and other methods without array
// Function declaration function fn() { console.log(arguments); //It stores all the passed arguments console.log(arrguments.length); // 3 console.log(arrguments[2]); // 3 } // function call fn(1,2,3);
For example: use the function to find the maximum value of any number
function maxValue() { var max = arguments[0]; for (var i = 0; i < arguments.length; i++) { if (max < arguments[i]) { max = arguments[i]; } } return max; } console.log(maxValue(2, 4, 5, 9)); // 9 console.log(maxValue(12, 4, 9)); // 12
??, Function calls another function
Because each function is an independent code block used to complete special tasks, it is often used to call each other. The specific demonstration will be shown in the following function exercise.
1.6 function exercise
1. Flip any array by function encapsulation
function reverse(arr) { var newArr = []; for (var i = arr.length - 1; i >= 0; i--) { newArr[newArr.length] = arr[i]; } return newArr; } var arr1 = reverse([1, 3, 4, 6, 9]); console.log(arr1);
2. Use function encapsulation to sort arrays - bubble sort
function sort(arr) { for (var i = 0; i < arr.length - 1; i++) { for (var j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j+1]) { var temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; }
3. Enter a year to judge whether it is a leap year (leap year: it can be divided by 4 and cannot be divided by 100 integers, or it can be divided by 400)
function isRun(year) { var flag = false; if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) { flag = true; } return flag; } console.log(isRun(2010)); console.log(isRun(2012));
4. The user inputs the year and outputs the number of days in February of the current year. If it is a leap year, February is 29 days; if it is a normal year, February is 28 days
function backDay() { var year = prompt('Please enter the year:'); if (isRun(year)) { //Parentheses are required to call the function alert('You entered' + year + 'It's a leap year. There are 29 days in February'); } else { alert('You entered' + year + 'It's not a leap year. February has 28 days'); } } backDay(); //Judge whether it is a function of leap year function isRun(year) { var flag = false; if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) { flag = true; } return flag; }
1.7. Two declaration methods of function??
1.7.1. User defined function mode (named function)??
Use the function keyword function to customize the function mode.
// Declaration definition method function fn() {...} // call fn();
-
Because of its name, it is also called named function
-
The code calling the function can be placed either in front of or behind the declared function
1.7.2. Function expression method (anonymous function)??
The function expression method is as follows:
// This is a function expression. Anonymous functions end with semicolons var fn = function(){...}; // The function call must be written below the function body fn();
-
Because the function has no name, it is also called anonymous function
-
This fn stores a function
-
The code of the function call must be written after the function body
2. Scope??
Generally speaking, the name used in a piece of program code is not always valid and available, and the scope of code that limits the availability of this name is the scope of this name. The use of scope improves the locality of program logic, enhances the reliability of program and reduces name conflict.
There are two scopes in JavaScript (before ES6):
- global scope
- Local scope (function scope)
2.1. Global scope??
It acts on the environment of all code execution (inside the whole script tag) or an independent js file
2.2. Local (function) scope??
The code environment acting on the function is the local scope. Because it is related to functions, it is also called function scope
2.3. JS has no block level scope??
-
Block scope is included by {}
-
In other programming languages (such as Java, c# etc.), variables created in if statements and loop statements can only be used in this if statement and loop statement, such as the following java code:
if(true){
int num = 123;
System.out.println(num); // 123
}
System.out.println(num); // report errors
There is no block level scope in JS (before ES6)
if(true){ int num = 123; System.out.println(num); // 123 } System.out.println(num); // 123
3. Scope of variable??
In JavaScript, variables can be divided into two types according to different scopes:
- global variable
- local variable
3.1. Global variable??
Variables declared under the global scope are called global variables (variables defined outside the function)
-
Global variables can be used anywhere in the code
-
The variables declared by var under the global scope are global variables
-
In special cases, variables that are not declared with var in the function are also global variables (not recommended)
3.2. Local variable??
Variables declared under the local scope are called local variables (variables defined inside the function)
-
Local variables can only be used inside this function
-
The variables declared by var inside the function are local variables
-
The formal parameters of a function are actually local variables
3.3. Differences??
-
Global variable: it can be used anywhere. It will be destroyed only when the browser is closed, so it takes up more memory
-
Local variable: only used inside the function. When the code block in which it is located is executed, it will be initialized; The contemporary code block will be destroyed after running, so it saves more memory space
4. Scope chain??
-
As long as it is code, there is at least one scope
-
What is written inside a function is called a local scope
-
If there are functions in the function, another scope can be born in this scope
-
According to the mechanism that internal functions can access external function variables, using chain search to determine which data can be accessed by internal functions is called scope chain
//Scope chain: the internal function accesses the variables of the external function and uses the chain search method to decide which value to take. This structure is called scope chain list
var num = 10;
Fusion fn() {/ / external function
var num = 20;function fun() { //Internal function console.log(num); // 20. First level visit }
}
- Scope chain: use the proximity principle to find the final value of the variable.
5. Pre resolution??
First, let's look at a few pieces of code and results:
console.log(num); // What's the result? //Error num is undefined console.log(num); // What's the result? var num = 10; // undefined // Named function (custom function mode): if we put function call on function declaration fn(); //11 function fn() { console.log('11'); } // Anonymous function (function expression): if we put function call on function declaration fn(); var fn = function() { console.log('22'); // report errors } //It is equivalent to executing the following code var fn; fn(); //fn no assignment, no this, an error is reported var fn = function() { console.log('22'); //report errors }
Javascript code is executed by the JavaScript parser in the browser. The JavaScript parser runs JavaScript code in two steps: pre parsing and code execution.
-
Pre parsing: the js engine will promote all var and function s in js to the front of the current scope
-
Code execution: executing JS statements from top to bottom
Pre parsing only occurs on variables and functions defined through var. Learning pre parsing can let us know why the value of the variable accessed before the variable declaration is undefined and why the function can be called before the function declaration.
5.1. Variable pre analysis (variable promotion)??
Variable pre parsing is also called variable promotion and function promotion
Variable promotion: the declaration of the variable will be promoted to the top of the current scope, and the assignment of the variable will not be promoted
console.log(num); // What's the result? var num = 10; // undefined //It is equivalent to executing the following code var num; // The variable declaration is promoted to the top of the current scope console.log(num); num = 10; // The assignment of variables will not be promoted
5.2. Function pre parsing (function promotion)??
Function promotion: the declaration of the function will be promoted to the top of the current scope, but the function will not be called.
fn(); //11 function fn() { console.log('11'); }
5.3. Solve the problem of function expression declaration and call??
For function expression declaration calls, remember that function expression calls must be written below the function declaration
// Anonymous function (function expression): if we put function call on function declaration fn(); var fn = function() { console.log('22'); // report errors } //It is equivalent to executing the following code var fn; fn(); //fn no assignment, no this, an error is reported var fn = function() { console.log('22'); //report errors }
5.4 pre analysis exercise??
The pre parsing part is very important and can be understood through the following four exercises.
Teacher Pink's video explanation pre analysis: https://www.bilibili.com/video/BV1Sy4y1C7ha?p=143
// Exercise 1 var num = 10; fun(); function fun() { console.log(num); //undefined var num = 20; } // The end result is undefined
The above code is equivalent to performing the following operations
var num; function fun() { var num; console.log(num); num = 20; } num = 10; fun();
// Exercise 2 var num = 10; function fn(){ console.log(num); //undefined var num = 20; console.log(num); //20 } fn(); // The end result is undefined 20
The above code is equivalent to performing the following operations
var num; function fn(){ var num; console.log(num); num = 20; console.log(num); } num = 10; fn();
// Exercise 3 var a = 18; f1(); function f1() { var b = 9; console.log(a); console.log(b); var a = '123'; }
The above code is equivalent to performing the following operations
var a; function f1() { var b; var a b = 9; console.log(a); //undefined console.log(b); //9 a = '123'; } a = 18; f1();
// Exercise 4 f1(); console.log(c); console.log(b); console.log(a); function f1() { var a = b = c = 9; // Equivalent to var a = 9; b = 9; c = 9; There is no var declaration in front of B and C. when looking at global variables // Collective declaration var a = 9,b = 9,c = 9; console.log(a); console.log(b); console.log(c); }
The above code is equivalent to performing the following operations
function f1() { var a; a = b = c = 9; console.log(a); //9 console.log(b); //9 console.log(c); //9 } f1(); console.log(c); //9 console.log(b); //9 console.log(a); //Error a is a local variable