Recursive and callback functions of JavaScript programs

Keywords: Javascript Front-end

Iife (self executing function)

IIFE (Immediately Invoked function Expression) is a function expression called immediately. This function is called immediately when it is declared.

The so-called self executing function, as the name suggests, is a function that is executed immediately after definition. Generally, it has no name and will only be executed once.

//If it starts with function, it requires a name, which is not declared in the form of an expression.
function (){//The error reported here is: the function needs a name.
    console.log('foo');
}();

We often use the following two methods:

(function xiaoGuaiGuai(){
        console.log('foo!!!');
    }());
//This method is the most commonly used.
(function(){
    console.log('foo@@@');
})();

The role of parentheses:

  • Grouping operators. (divide data into groups)

    (1+2)*3

  • Function Caller: when the previous thing can get a function value.

A function expression called immediately can only be run once. Reason: indeed, it is still a reference type, but it has no identification. After execution, it will be recycled by the garbage collection mechanism.

Call immediately after definition and release immediately after call.

Even two IIFE functions with exactly the same code have different execution environments and different functions.

The IIFE function itself will not be promoted, but the code inside the function will be promoted.

If you want to pass a value to IIFE, you only need to pass in the argument at the function Caller:

(function(name){
    console.log(name+'It's handsome!');
})('Tutu's father');

Use (to understand):

  1. Initialize the project in the project. As soon as you enter the program, you will initialize the project. After initialization, it will not be used, so it will be released.
  2. IIFE is also widely used in frameworks, modules and libraries. Because this can be used to initialize the project and expose only the modules that need to be exposed.

Recursive call of function

How functions are used

  1. The protagonist is always Xiaojun.
  2. Xiao Jun went to do another thing before he finished one thing.
  3. The appearance of little beauty is actually a termination condition (roll)
  4. After the current thing is done, you will do what you didn't do last time. Until everything is done.

If the same function is called multiple times, the execution environment is different (the allocated address space is different), and the same variables in each execution environment have no relationship.

Pass: go in

GUI: come out

be careful:

  1. You are this function, you call yourself. When you finish a present thing, you will do what you didn't finish last time.
  2. Recursion must have a conditional limit, otherwise it will fall into its own nest and never turn over.
  3. Not sure how many times to call.

example:

  1. Find the sum of 1 ~ 5, using recursion.

    If you can use less global variables in the coding process, you can use less global variables.

  2. Count the number of elements in the array.

    Judge array: array.isarray (variable). If it is an array, return true; otherwise, return false.

    var arr = [1, [5, 4, 6], 9, [4, 5, [0, 2, [7, 3]]]];
    
        function ARR(arr) {
          var sum = 0;
          for (var i = 0; i < arr.length; i++) {
            if (Array.isArray(arr[i])) {
              sum += ARR(arr[i]);
            } else {
              sum++;
            }
          }
          return sum;
        }
        console.log(ARR(arr));
    

Callback of function (callback function)

The essence of callback function: a function is an object and a value, which can be passed into a function as a parameter.

Knowledge points for learning callback functions:

  • When a reference type is assigned to a variable, the variable stores the address of the reference type.

    A reference type can have multiple names. One changes the value of the reference type, and the value of the other also changes.

    var a = [];
        a[0] = 'Apple';
        var b = a;//The addresses of a and b point to the same.
        console.log(b);
    
        function foo(){
        }
        var foo1 = foo;//The same one.
    
  • If the parameter of the function is a common type, the value is passed, and the reference type is the address.

    function test(arr){//arr=0x123
            arr[arr.length] = 'Little banana';
        }
        var a = ['Little apple'];//0x123
        test(a);//test(0x123)
        console.log(a);//['little apple', 'little banana']
    
  • A function itself is a value and an object, which can be passed into the function as an argument.

  • A function itself is a value and an object, so it can be returned as a return value.

    function foo(){//0x123
        function bar(){//0x234
            console.log('foo---->bar');
        }
        return bar;//0x234
    }
    var res = foo();//res=0x234
    res();//0x234()
    

What is a callback function

A callback function is considered a high-level function, which is passed as a parameter to another function (a). The callback function will be called and executed in a.

The essence of callback function is a pattern and a routine to solve problems.

Use of callback functions

  • Event listening and processing.
  • Set timeout and time interval.
  • Ajax.
  • Various lifecycle callback functions in the framework.
  • Generalization: the code is concise and easy to expand.
<script>
    //General function
    function getNumber(num, fn) {//num=3;fn=0x123
        /*
        i=1 1<=3 true
            fn(1);//false
            console.log(1);
        i=2 2<=3 true
            fn(2);//true
        i=3 3<=3 true
            fn(3);//false
            console.log(3);
        i=4 4<=3 false
        */
        for (var i = 1; i <= num; i++) {
            if (fn(i)) {
                continue;
            }
            console.log(i);
        }
    }

    //Rule 1: even
    function rules1(n) {//0x123
        if (n % 2 == 0) {
            return true;
        } else {
            return false;
        }
    }

    // getNumber(3,rules1);//getNumber(3,rules1)

    //Rule 2: and 4 are reserved if the remainder is 0
    function rules2(n){
        if (n%4!=0){
            return true;
        }else {
            return false;
        }
    }
    // getNumber(10,rules2);

    //Copy it by hand 10 times.
    
    //Rule 3: remove odd numbers
    getNumber(10,function(n){
        if (n % 2 == 0){
            return false;
        } else{
            return true;
        }
    });
</script>

In this example, you can see that after extracting functions, various rules are also extracted, which reduces coupling and is easy to expand.

Posted by Zooter on Fri, 19 Nov 2021 04:48:26 -0800