I. Introduction of functions

Function: Encapsulates some functions or statements and executes these statements by calling them when needed.

  • A function is also an object.
  • When a typeof() function is used to examine a function object, function is returned
  • The use of the function containsTwo steps:
    • Define functions – Encapsulate individual functions
    • Call functions – enjoy the fruits of encapsulation

1.2 Define a function

  • The process of defining a function is the process of encapsulating some functionality
  • Later in the development, we will define many of our own functions according to our own needs

1.3 Call a function

  • Calling a function makes an existing function available to us
  • These functions can be functions that have just been wrapped themselves
  • Of course, we can also use JavaScript or other functions defined by third party libraries.

1.4 Functions

  • == Write a large number of repeated statements in the function. When using these statements in the future, you can directly call the function to avoid repeated work. = =
  • == Simplify programming and make programming modular. = =

1.5 examples of functions

  • Calculation of 1 + 2 + 3 + 4 + 5 + 6 + 7… + 100?

  • var sum=0;
    function sumN(){
        for(var i=1; i<=100; i++){ sum+=i; }return sum;
    }
    console.log(sumN(100));/ / 5050
    Copy the code

2. Function definition and call

2.1 Definition of functions

2.1.1 Use the == function declaration == to call a function.

  1. Grammar:

    Function Function name ([parameter 1, parameter 2,....] ){// Parameters are optional. Note: Brackets in syntax indicate "optional" statements; }Copy the code
  2. The characteristics of

    1. I don’t like the idea of “function “.

    2. Function names: The naming conventions are the same as for variables. The value can contain only letters, digits, underscores (_), and $($), and cannot start with a digit

    3. Parameter: Optional.

    4. Inside the curly braces is the statement for this function.

    5. The method definition is that the type of the parameter is not written, nor is the return value type.

    6. A method is an object that is overridden if a method with the same name is defined

    7. In JS, methods are called only with respect to the name of the method, not the argument list

    8. There is a hidden built-in object (array) in the method declaration, arguments, that encapsulates all the actual arguments

2.2.2 Create a function using the == function expression ==.

  • Previously defined functions are called declarations of functions, and there are other forms of function besides declarations:
    • Function expressions: == Anonymous function expressions and named function expressions ==
  • The name attribute of the function:All functions have a name attribute that gets the name of the function
    • * The name attribute of the function declaration: the function name
    • The name attribute of a named function expression: the function name
    • The name attribute of an anonymous function expression: the variable name

Grammar:

Var =function([parameter 1, parameter 2,....]) ){// Parameters are optional statements; }Copy the code
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, </title> </head> <body> </body> </body> <script> /* 一 Named function expression 2. Anonymous Function expression 2: Function attribute name 3.1 Name attribute in function declaration Mode: Function name 3.2 Name Attribute in Named Function Expression: Function name 3.3 Name Attribute in Anonymous Function Expression: Function func() {console.log(" I am the way the function is declared "); } func(); Var hasName = function test() {console.log(" I am a named function expression "); } hasName(); Var noName = function () {console.log(" I am an anonymous function expression "); } noName(); //3. Function attributes: name console.log(func.name); //func console.log(hasName.name); //test console.log(noName.name); //noName </script> </html>Copy the code

2.2.3 Execute the function immediately

Function ([parameter 1, parameter 2,....] ){// Parameters are optional statements; }) ()Copy the code
  • Analogous function expressions: ==(the parentheses are equivalent to an anonymous function **)(the parentheses are passing parameters)**==
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title> function declaration and call </title> <script> /* function declaration and call 1. 1.1 Use function declarations to create a function syntax: function Function name (parameter 1, parameter 2,....) {// Parameters are optional statements; */ function func1(){console.log(" I am a function declaration "); }; Var func2=function(){console.log(" I am a function of function expression form "); }; Console. log(" I am an immediate function "); (function(){console.log(" I am an immediate function "); }) (); func1(); func2(); </script> </head> <body> </body> </html>Copy the code

2.2 Function parameters and arguments

Function add(a,b){//a,b is the formal argument return a+b; } console.log(add(10,20)); //30 console.log(add("10","20")); //1020 console.log(add("hello","World")); / / helloWorld console. The log (add (1, 2, 3, 4, 5)); //3, there are only two parameters, the extra parameters are invalidCopy the code

2.2.1 parameter

  • One or more parameters can be specified in () of a function
  • Parameters are separated by commas. Declaring parameters is like declaring the corresponding variables inside the function, but not assigning values

2.2.2 argument

  • When calling a function, you can specify arguments in ()
  • The argument will be assigned to the corresponding parameter in the function
2.2.2.1 Types of arguments
  • The arguments to a function can be any data type
  • When using a function, the parser does not check the type of the argument, so you need to be aware that it is possible to check the type of the argument
2.2.2.2 Number of arguments

Note: JS does not check for arguments actually passed to the function. A value can be passed, no value can be passed, or any number of values can be passed

The parser also does not check the number of arguments when calling a function:

  • == Redundant arguments are not assigned to ==

  • == If the number of arguments is less than the number of parameters, the parameter with no corresponding argument will be undefined.==

  • Such as:

2.2.3 the arguments

Arguments can be used to get all the arguments actually passed

Case study:

var total=0; var sum=function(){ console.log(arguments); for(var i=0; i<arguments.length; i++){ total+=arguments[i]; } return total; } var result = sum (6); //21 console.log(result);Copy the code

The return value of the function

function sum(a,b){ return a+b; } the sum (10, 20);Copy the code

Return terminates the method.

Note:

  • The value after the return will be the result of the function execution. You can define a variable to receive the result

  • None of the statements after the return in a function are executed (the function stops and exits immediately after the return statement is executed)

  • If the return statement is not followed by any value, it returns undefined

  • If the function does not write return, undefined is also returned

  • The return value can be any data type, object or function.

    • Function sum(a,b){var add=function(){return a+b; } return add; // Return add(); //30, this is the function call} console.log(sum(10,20));Copy the code

Function name, function body, and function loading problem (important) ==

  • Function name == entire function

    • Var add=function(a,b){return a+b; } console.log(add)==console.log(function(a,b){ return a+b; });Copy the code
  • We know that when we call a function, we usually use the function () format; But at this point, we’re using the function format, which acts as the whole function.

  • Function loading problem: when JS loads a function, only the name of the function is loaded, so if you want to use internal member variables, you need to call the function.

The difference between fn() and fn(important) ==

  • Fn (): call the function, equivalent to the return value of the function.
  • Fn: function object, equivalent to directly obtain the function object

Execute the function immediately

  • What is an immediate function?

    • Professional name: Immediate-Invoked Function Expression (IIFE Immediately Invoked Function Expression)
  • The expression means that a function is executed as soon as it is defined

    • The first part defines an anonymous function that has its own independent execution context.

    • The second part, followed by (), indicates that the function was executed

  • What does this thing do?

    • == creates a separate execution context, preventing external access to or modification of internal variables, as well as modification of internal variables

6.1 Execute the other writing of the function immediately

  • The immediate function must be an expression, not a function declaration:

    • This is an error because it is a function declaration, not a function expression
    • When parentheses appear at the end of an anonymous function to call a function, it defaults to treating the function as a function declaration.

  • When parentheses wrap a function, it defaults to parsing the function as an expression rather than a function declaration.

  • The following is a function expression, so it can be executed

  • A declarative function executes two ways of writing a function immediately

    • (function () {console.log(" I'm a declarative function "); }) ()Copy the code
    • (function () {console.log(" I'm a declarative function "); } ());Copy the code
<script> /* Execute function immediately: the function is executed immediately after it is defined. /* function func() {console.log(" I am a declarative function "); } // add () to the function; /* (function func() {console.log(" I am a declarative function "); })() func(); Function () {console.log(" I am a declarative function ");} // add () (function () {console.log(" I am a declarative function "); } ()); (function () {console.log(" I'm a declarative function "); Var test = function () {var test = undefined; Because the function returns undefined console.log by default (" I am an anonymous function expression "); return undefined; } (); // The anonymous function expression immediately executes the function call console.log(test); //undefined </script>Copy the code

Immediately execute the following function:

Var result=(function(a,b){return a+b; }) (10, 20); console.log(result);Copy the code

Method seven.

Functions can also be properties of objects. ** If a function is stored as a property of an object, then we call that function a method of that object. ** Calling this function calls the method of the object. This is the name of the method, and nothing else.

Function examples:

// call the function fn();Copy the code

Method examples:

// Call the method obj.fn();Copy the code

We can say that if fn() is used directly, it is a function call. If xx.fn () is found, it is a method call

Eight. This keyword

Each time a function is called, the parser passes inside the function a tough argument. The implicit argument is this, which refers to an object we call the context object in which the function is executed.

This refers to a different object depending on how the function is called: ==

  • 1. When called as a function, this is always window. Such as fun (); Equivalent to window.fun ();

  • 2. When called as a method, this is the object on which the method is called

  • 3. When called as a constructor, this is the newly created object

  • 4. When called with call and apply, this is the specified object

    For example:

    <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <script> /* this keyword -1. When called as a function, this is always window. Such as fun (); Equivalent to window.fun (); - 2. When called as a method, this is the object on which the method was called - 3. When called as a constructor, this is the newly created object - 4. / var Student={name:" Jason ", age:20, like:function(){console.log(this); / var Student={name:" Jason ", age:20, like:function(){console.log(this); // This is the Student object console.log(this.name+" like fishing "); } } var fn=Student.like; var fn1=function(){ console.log(this); // This is the Student object console.log(this.name+" like fishing "); } console.log("-------------------------------"); console.log(fn==fn1); Console. log(fn== student.like); //true console.log(fn()); console.log(Student.like()); //this->Student Student.like(); //this->window </script> <body> </body> </html>Copy the code

8.1 Change the direction of this

Format:

1. Call (object); 2. 2. Function name. Apply (object); 3.bind();Copy the code
  • There are three ways to change this: apply, call, and bind

  • The difference between Apply and call is that the values passed by apply are arrays, while the values passed by call are written directly

  • /* Change the pointer to this: 1. 2. Function name. Apply (object); 3.bind(); */ var Student={ name:"jason", like:function(){ console.log(this); The console. The log (enclosing the name + "phishing"); } } //Student.like(); Var fn= student.like; fn(); //this points to window console.log(window.fn===fn); Var teacher={name:" ",} //call; //fn.call(teacher); fn.apply(teacher)Copy the code

== use case of apply,call,bind: ==

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, > <title>Document</title> <script> /* */ var Student={name:" 王", like:function(){console.log(this.name+" 王"); for(var i=0; i<arguments.length; i++){ console.log(arguments[i]); }}. Bind (Teacher),} var Teacher={name:" ",} //Student. Like. Call (Teacher," sing "," dance ","rap"); //Student. Like. Apply (Teacher,[" sing "," dance ","rap"]); Student. Like (" sing "," dance ","rap"); </script> </head> <body> </body> </html>Copy the code

9. The arguments

When calling a function, the browser passes two implicit arguments each time:

  • 1. Function context object this
  • 2. Encapsulate object arguments for arguments

Such as:

var abc=function(){
   console.log(arguments);
   console.log(typeof arguments);
 }
 abc();
Copy the code

Arguments is an array-like object that manipulates data by index and also gets length.

Arguments stand for arguments. At function call time, arguments we pass are stored in arguments and can only be used within functions

4.1 Return the number of function arguments: arguments.length

Arguments. length can be used to get the length of the argument.

4.2 Returns the function being executed: arguments.callee

Arguments has a property called callee that corresponds to the function object to which it is currently pointing.

When using recursive function calls, it is recommended to use arguments.callee instead of the function name itself.

4.3 Arguments can modify elements

Arguments can change elements, but not the length of an array of elements.

For example:

Var ABC =function(a,b,c,d){console.log(arguments); console.log(typeof arguments); //Object // length console.log(arguments.length); //4 console.log(arguments.callee); // // change element if(arguments[0]){arguments[0]=100; } console.log(arguments); console.log(a); } ABC (1,2,3,4);Copy the code

3.1 Function: Function (method) object

Function fun4(a,b,c){//document.write(a+b+c); document.write(c); //fun4(1,2); //fun4(1,2); function fun5(a,b){ document.write(arguments[2]); //fun5(1,2,3); //fun5(1,2,3);Copy the code
Function sum(){var total=0; function sum(){var total=0; Var I = 0; var I = 0; i <arguments.length ; i++) { total += arguments[i]; } return total; } the document. The write (sum (1, 2, 3, 4, 5)); ` ` `Copy the code

X. Function exercises

10.1 Exercise 1: Implementing an Adding calculator

 function addCalculate() {
      var total = 0;
      for (var i = 0; i < arguments.length; i++) {
        total += arguments[i];
      }
      return total;
    }
    console.log(addCalculate(10, 30, 60));
Copy the code

10.2 Exercise 2: Define a function passing in the width and height to calculate the area of the rectangular region

/ var square = function (width, height) {return width * height; } var s = square(30, 10); console.log(s); </script>Copy the code

10.3 Exercise 3: Define a function and pass in the radius to calculate the area of a circle

/** * Define a function, pass in the radius, / var circleSquare = function (radius) {return radius * radius * math.pi} console.log(circleSquare(1)); </script>Copy the code

10.4 Exercise 4: Define a function that evaluates the sum of numbers 1 to n, passing in n as a positive integer

*/ function getNumberSum(num) {var total = 0; for (var i = 1; i <= num; i++) { total += i; } return total; } console.log(getNumberSum(10)); //55 </script>Copy the code

10.5 Exercise 5: Define a function, pass in an array, and flip the array

/ var reverseArray = function (arr) {var temp; for (let i = 0; i < arr.length / 2; i++) { temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } return arr; } var arr = [10, 1, 3, 50, 6]; arr = reverseArray(arr); console.log(arr); / /,50,3,1,10 [6] < / script >Copy the code

10.6 Exercise 6: Define a function that passes in an array of numbers and sorts the numbers in the array

*/ var arraySort = function (arr) {var temp; For (let j = 0; j < arr.length - 1; j++) { for (let i = 0; i < arr.length - 1; i++) { if (arr[i] >= arr[i + 1]) { temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } } } return arr; } var arr = new Array(20, 5, 30, 1, 6); arr = arraySort(arr); console.log(arr); / /,5,6,20,30 [1] < / script >Copy the code

10.7 Exercise 7: Define a function, pass in a number, and find the corresponding Fibonacci sequence

< script > / * practice 7: define a function, introduced to a number, and the corresponding thin wave cut the sequence of the Fibonacci sequence refers to such a sequence: 0,1,1,2,3,5,8,13,21... The sequence starts with the third term, and each term is equal to the sum of the previous two terms. */ //var temp = 0; var arr = []; var fArr = function (n) { for (let i = 0; i < n; i++) { if (i == 0) { //temp = 0; arr.push(0); } else if (i == 1) { //temp = 1; arr.push(1); } else { if (i <= n) { // temp += 0 + 1; //arr.push(temp); arr[i] = arr[i - 2] + arr[i - 1]; Push (arr[I]); // Arr. Push (arr[I]); } else { break; } } } return arr; } console.log(' pass ${10}, find the corresponding Fibonacci sequence ', fArr(10)); </script>Copy the code

<script> function f(n) { var sum = 1; for (let i = 0; i < n; i++) { if (i == 0) { var num1 = 0; } else if (i == 1) { var num2 = 1; } else { sum = num1 + num2; num1 = num2; num2 = sum; } } return sum } console.log(f(6)); / / 5Copy the code

11. Recursion

<script> /* Recursive call 1.1 A function can call another function 1.2 A function call itself is recursive 1.3 Avoid using recursion as much as possible in development: Function test01() {console.log("test01 function "); function test01() {console.log("test01 function "); test02(); } test01(); Function test02() {console.log("test02 "); Function test() {//console.log('test function '); Running out of memory test() without end conditions } test(); </script>Copy the code
Function f(n) {if (n === 1) {return 0} else if (n === = 2) {return 1; } else { return f(n - 1) + f(n - 2); } } console.log(f(6)); //5 </script>Copy the code

Twelve.Function call stack

Global and local variables

  • There was no concept of block-level scope in JavaScript (prior to ES5), but functions could define their own scope.
  • What are global variables and local variables?
    • Variables defined inside a function are called local variables. = =
    • Variables defined in script tags are called global variables. = =
  • In a function, what is the order in which variables are accessed?
    • == has priority access to variables in its own function, if not found, access globally. = =

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title> Variable scope </title> </head> <body> </body> <script> /* 1. Variable scope: The scope in which a variable can be used. This scope is variable scope 2. There was no concept of block-level scope in JavaScript (prior to ES5), 3. But functions can define their own scope. 4. What are global variables and local variables? Variables defined inside a function are called local variables. Variables defined in script tags are called global variables. By default, local variables cannot be accessed globally. In functions, what is the order in which variables are accessed? */ //1 */ /1 */ /1 */ /1 Block has no scope of its own var age = 18; { var name = "jason"; } console.log(name, age); Function getName() {var name = "Tom "; function getName() {var name =" Tom "; var age = 20; console.log(age); //20 } </script> </html>Copy the code

Value passing and reference passing

1. Data types in JavaScript can be divided into two types:

  • Primitive data type value primitive type, such as Undefined, Null, Number, Boolean, String.
  • Values of a reference type, that is, Object type Object type, such as Object, Array, Function, Date, etc.

2. Different memory allocations when declaring variables

  • Raw values: Simple segments of data stored in the stack, that is, their values are stored directly where the variable is accessed. This is because these primitive types take up a fixed amount of space, so they can be stored in a smaller area of memory – the stack. This storage facilitates quick lookup of the value of the variable.
  • Reference value: An object stored in the heap, that is, the value stored in a variable is a pointer to the memory address where the object is stored. This is because the size of the reference value changes, so it cannot be placed on the stack, which would slow down variable searches. Instead, the value placed in the stack space of a variable is the address of the object stored in the heap. The size of the address is fixed, so storing it on the stack has no negative impact on variable performance.

14.1 Transfer by Value

Function test(n) {n = "kobe"; } var name = 'why'; test(name); console.log(name); //whyCopy the code

14.2 Passing by Reference

Function func(arr) {arr[0] = "Jason "; } var array = [1, 2, 3]; func(array) console.log(array); / / [' Jason, 2, 3]Copy the code