JavaScript advanced (3)

Time:2021-5-3

Three styles of creating functions

1. Common function declared by function (named function)
2. Function expression (anonymous function)
3.new Function()

Var FN = new function (‘parameter 1 ‘,’parameter 2’,…,’function body ‘);

  • The parameters in function () are in string format
  • The third way is less efficient and inconvenient to write, so it is less used
  • All functions are instance objects of fnction
  • Functions also belong to objects
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    The definition and calling method of < title > function
</head>
<body>
<script>
    //Custom mode
 function fn() {
    }
    //Function expression
 var fn = function() {
    }
    //Using new function ('parameter 1 ','parameter 2','function body ')
 var f = new Function('a','b','return a+b')
    console.log(f(1,2));
    console.dir(f);
    //Used to determine whether f is an object
 console.log(f instanceof Object)
</script>
</body>
</html>

JavaScript advanced (3)

Calling methods of different functions

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
< button > button
</body>
<script>
    //How to call a function
 //1. Ordinary function call
 function fn() {
        console.log('hello word')
    }
    fn()
    //2. Function call of object class
 var obj = {
        say: function () {
            return 'hello word'
 }
    }
    console.log(obj.say())
    //3. Call of constructor
 function Star(name, age) {
        this.name = name;
        this.age = age;
    }
    Var star1 = new star ('yaozimo ','18');
    console.log(star1.name)
    //4. Call of event function
 var bth = document.querySelector('button');
    bth.addEventListener('click', function () {
        Console.log ('event function ')
    })
    //5. Timer function
 setInterval(function () {
        Console.log ('timer function ')
    }, 5000)
</script>
</html>

JavaScript advanced (3)

Self executing function

As the name suggests: the function you call

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    < title > self executing function
</head>
<body>
<script>
    (function () {
        alert('hello word')
    })()
</script>
</body>
</html>

JavaScript advanced (3)

The direction of this

Function internal this point, when we call to determine

Note: in the self executing function, this points to window
JavaScript advanced (3)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        This of the < title > function points to < / Title >
    </head>
    <body>
        < button > button
    </body>
    <script>
        //How to call a function

        //1. Ordinary function call
        function fn() {
            console.log(this) //windows

        }

        fn()
        //2. Function call of object class
        var obj = {
            say: function() {
                Console. Log (this) // points to o
            }
        }
        obj.say()

        //3. Call of constructor
        function Star(name, age) {
            Console.log (this) // this in the constructor points to its instantiated star
            this.name = name;
            this.age = age;

        }

        Var star1 = new star ('yaozimo ','18');
        //4. Call of event function
        var bth = document.querySelector('button');
        bth.addEventListener('click', function() {
            Console.log (this) // this in the event function points to its caller BTH button
        })

        //5. Timer function
        setInterval(function() {
            Console.log (this) // this in the timer points to windows
        }, 5000)
    </script>
</html>

JavaScript advanced (3)

Call() method

The call () method calls an object. It is simply understood as the way to call a function, but it can change the this direction of the function.

fun.call(thisArg, arg1, arg2, …)

  • Thisarg: this value specified when the fun function runs
  • Arg1, arg2: other parameters passed
  • The return value is the return value of the function, because it is the calling function
  • Therefore, when we want to change this point and call this function, we can use call, such as inheritance
<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>call()</title>
    </head>

    <body>

    </body>
    <script>
        //Change the call () method that this points to inside the function
        var o = {
            name: "andy"
        };

        function fn(a, b) {
            console.log(this); //o
            console.log(a + b); //3
        }

        The FN. Call (O, 1, 2) // call method can not only change the internal this direction of a function, but also pass parameters


        //Call () method is mainly for inheritance


        function Father(name, age, sex) {
            console.log(this)
            this.name = name;
            this.age = age;
            this.sex = sex;

        }

        function Son(name, age, sex) {
            Father.call(this, name, age, sex)
        }

        Var son = new son ('andy Lau ',' 18 ', male');
        console.log(son)
    </script>

</html>

JavaScript advanced (3)

###Apply () method

The apply () method calls a function. It is simply understood as the way to call a function, but it can change the this direction of the function.

fun.apply(thisArg, [argsArray])

  • Thisarg: this value specified when the fun function runs
  • Argsarray: the value passed must be included in the array
  • The return value is the return value of the function, because it is the calling function
  • Therefore, apply is mainly related to arrays. For example, use math. Max() to find the maximum value of an array
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    < title > change this point in the function to apply() < / Title > function
</head>

<body>

</body>
<script>
    var o = {
        name: 'andy'

    }

    function fn(arr) {
        console.log(this); // At this time, this points to 0;
        console.log(arr)

    }

    fn.apply(o, ['pink']); // Note: the second argument must be an array

    //You can use the array method to achieve the maximum value of the array
    var arr2 = [1, 66, 22, 55, 108];
    var max = Math.max.apply(Math, arr2);
    var min = Math.min.apply(Math, arr2);
    console.log(max, min)
</script>

</html>

JavaScript advanced (3)

bind()

The bind() method does not call the function. But it can change the direction of this in the function

fun.bind(thisArg, arg1, arg2, …)

  • Thisarg: this value specified when the fun function runs
  • Arg1, arg2: other parameters passed
  • Returns the copy of the original function modified by the specified this value and initialization parameter
  • Therefore, when we just want to change this point and do not want to call this function, we can use bind ()
<!DOCTYPE html>
  <html lang="en">
    <head>
        <meta charset="UTF-8">
        < title > change the bind() method that this points to inside the function

    <body>
        < button > button
        < button > button
        < button > button
    </body>
    <script>
        //The bind () method means to bind
        var o = {
            name: "andy"
        }

        function fn(a, b) {
            console.log(this)
            console.log(a + b)
        }

        //Note: the bind() method will change this inside the function, but will not call the original function
        var f = fn.bind(o, 1, 2);
        f()

        //Case: when we click the button, we disable the button and turn it on again three seconds later
        var bths = document.querySelectorAll('button');
        for (var i = 0; i < bths.length; i++) {
            bths[i].onclick = function() {
                this.disabled = true;
                setTimeout(function() {
                    this.disabled = false
                    //This button here refers to BTH
                }.bind(this), 2000)
            }
        }
    </script>
</html>

JavaScript advanced (3)

The difference between call() apply() bind()

Differences:

  1. Call and apply will call the function and change the internal this point of the function
  2. The parameters passed by call and apply are different. The parameters passed by call are aru1, aru2.. the form of apply must be array form [Arg]
  3. Bind does not call the function, it can change the internal this point of the function

Main application scenarios:

  1. Call often does inheritance
  2. Apply is often related to arrays. For example, the maximum and minimum value of an array can be realized by means of mathematical objects
  3. Bind does not call the function, but also want to change this point. For example, change this point inside the timer

Strict model

The emergence of strict mode is to limit the nonstandard syntax in nonstandard strict mode and pave the way for ES6
Strict mode makes some changes to the normal JavaScript semantics:

  1. It eliminates some unreasonable and imprecise parts of JavaScript syntax and reduces some strange behaviors.
  2. Eliminate some unsafe parts of code operation, and ensure the safety of code operation.
  3. Improve the efficiency of compiler and increase the running speed.
  4. Some syntax that may be defined in the future version of ECMAScript is disabled to pave the way for the new version of JavaScript in the future. than

For example, some reserved words such as class, enum, export, extensions, import and super cannot be used as variable names

Open strict mode

Putting ‘use strict’ in a script or in a function is equivalent to turning on strict mode

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script type="text/javascript">
      //Turn strict mode on for scripts
        'use strict'
  </script>
  
  <script type="text/javascript">
        function fn(){
            //Turn on strict mode for functions
            'use strict'
        }
  </script>
</body>
</html>

Change of strict mode

  • In strict mode, variables must be declared before they can be used
  • This points to undefined in normal functions in strict mode
  • In strict mode, the constructor is not called new. This means undefined
  • This in timer points to window in strict mode
<!DOCTYPE html>
<html lang="en">
   <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <meta http-equiv="X-UA-Compatible" content="ie=edge">
       < title > changes in strict mode
   </head>
   <body>
       <script type="text/javascript">
           'use strict'
           //1. Variables must be declared before being used
           var num = 10;
           console.log(10);
           // delete  num;  Disable deleting variables in strict mode

           //2. This points to undefined in strict mode
           function fn() {
               Console. Log (this) // in strict mode, this means undefined
           }
           fn()
           //3. In strict mode, the constructor is not called new, this means undefined
           function Star() {
               console.log(this)
           }
           Star()

           //4. In strict mode, this of timer points to window
           setTimeout(function() {
               console.log(this)
           }, 2000)
       </script>
   </body>
</html>

JavaScript advanced (3)

Higher order function

A higher-order function is a function that operates on other functions. It takes a function as a parameter or outputs a function as a return value

<!DOCTYPE html>
<html>
   <head>
       <meta charset="utf-8">
       < title > higher order functions
   </head>
   <body>

   </body>
   <script>
       //Take the function as an argument
       function fn(callback) {
           callback && callback()
       }
       fn(function() {
           alert('hello word')
       })


       //Output function as return value
       function fn2() {
           return function() {}
       }
       console.log(fn2())
   </script>
</html>

JavaScript advanced (3)
In this case, FN () and FN2 are high price functions

Function is also a data type, which can be passed to another function as a parameter. The most typical one is callback function

<!DOCTYPE html>
<html>
   <head>
       <meta charset="utf-8">
       < title > higher order functions
       <style>
           * {
               margin: 0;
               padding: 0;
           }
           .box {
               position: absolute;
               top:0;
               left: 0;
               width: 200px;
               height: 200px;
               background-color: blueviolet
           }
       </style>
   </head>
   <script></script>
   <body>
       <div class="box"></div>
       
   </body>
   <script>
       $('.box').animate({
           left:200,
           top:200
       },function(){
           $(this).css('background','red')
       })
   </script>
</html>

JavaScript advanced (3)

closure

A function that has access to variables in the scope of another function

Action: extends the scope of a variable

<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        < title > closure
    </head>
    <body>
        <div></div>
    </body>
    <script>
        //The so-called closure is simply understood as having access to a local variable of another function
        function fn() {
            let num = 10;

            function fun() {
                console.log(num) //10
            }

            fun()
        }

        fn()
    </script>
</html>

JavaScript advanced (3)

JavaScript advanced (3)

Debugging closure in Chrome

  1. Open the browser and press F12 to start the chrome debugging tool.
  2. Set breakpoints.
  3. Find the scope option (meaning of scope scope).
  4. When we refresh the page again, we will enter breakpoint debugging. There will be two parameters (global global scope and local local scope) in scope.
  5. The closure parameter represents the closure function

The function of closure function

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        The function of < title > closure
    </head>
    <body>

    </body>
    <script>
        //A function that has access to a local variable of another function is called a local variable
        function fn() {
            var num = 10;
            return function() {
                console.log(num) //10
            }

        }

        var f = fn(); //fn()
        f(); // Call the function after return
    </script>
</html>

JavaScript advanced (3)

The output of the closure is the current index number

The core idea is to execute the function immediately

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        Click I output index number of < title > closure
    </head>
    <body>
        <ul class="nav">
            <li>one</li>
            <li>two</li>
            <li>three</li>
            <li>four</li>
        </ul>
    </body>
    <script>
        //The first method: click I to output the index number of current I
        var lis = document.querySelector('.nav').querySelectorAll('li');

        for (var i = 0; i < lis.length; i++) {
            lis[i].index = i; // Set the index number for Li of each loop

            lis[i].addEventListener('click', function() {
                console.log(this.index)
            })
        }

        //The second method is to use the closure to output the current index number

        for (var i = 0; i < lis.length; i++) {
            //Use the for loop to create four immediate functions, because the original function in the immediate function can use its variables

            (function(i) {
                lis[i].addEventListener('click', function() {
                    console.log(i)
                })
            }(i))

        }
    </script>
</html>

JavaScript advanced (3)

Timer of closure

Requirements: automatically display the contents of Li after three seconds

The core idea is to use the closure function generated by each for loop

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        < title > timer of closure
    </head>
    <body>
        <ul class="nav">
            <li>one</li>
            <li>two</li>
            <li>three</li>
            <li>four</li>
        </ul>
    </body>
    <script>
        var lis = document.querySelector('.nav').querySelectorAll('li');
        for (var i = 0; i < lis.length; i++) {

            (function(i) {
                setTimeout(function() {
                    console.log(lis[i].innerHTML)
                }, 5000)
            }(i))
        }
    </script>


</html>

JavaScript advanced (3)

Closure of the taxi price

The starting price of a taxi is 13 yuan (within 3 km). After that, 5 yuan will be added for every additional kilometer. Users can calculate the taxi price by inputting the number of kilometers

If there is congestion, the total price will be charged 10 yuan more

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        < title > the taxi price of closure
    </head>
    <body>
    </body>
    <script>
        let car = (function() {
            let star = 13; // Starting price of taxi
            let total = 0; // Total price local variable
            return {
                price: function(n) {
                    if (n <= 3) {
                        total = star
                    } else {
                        total = star + (n - 3) * 5
                    }
                    Return total // Note: don't forget to return the value
                },
                //Cost after congestion
                yd: function(flag) {
                    return flag ? total + 10 : total;
                }

            }

        })();
        console.log(car.price(5));
        Console.log (car.yd (true)) // if the parameter is true, it means that the plug is added 10 yuan


        console.log(car.price(6));
        console.log(car.yd(false))
    </script>
</html>

JavaScript advanced (3)

Test questions

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
<script>
    //Thinking question 1:

    var name = "The Window";
    var object = {
        name: "My Object",
        getNameFunc: function () {
            return function () {
                return this.name;
            };
        }
    };

    console.log(object.getNameFunc()())
    var f = object.getNameFunc();

    var f = function () {
        return this.name;
    }
    f();


    //Question 2:

    var name = "The Window";
    var object = {
        name: "My Object",
        getNameFunc: function () {
            var that = this;
            return function () {
                return that.name;
            };
        }
    };
    console.log(object.getNameFunc()())
</script>
</body>

</html>

JavaScript advanced (3)

Recursive function

If a function can call itself internally, it is a recursive function

Simple understanding: the function calls itself internally

The function of recursive function is the same as loop effect, it is easy to “stack overflow”, so we must add the exit condition return

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script>
    var num = 1;

    function fn() {
        console.log('hello word')
        if (num == 6) {
            Return // a recursive function must have an exit condition
        }
        num++
        fn()
    }

    fn()
</script>
</html>

JavaScript advanced (3)

Using recursion to find the factorial of 1 ~ n

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    < title > finding the factorial of 1-N by recursion
</head>
<body>

</body>
<script>
    function fn(n) {
        if(n==1){
            return 1
        }
        return  n *fn(n-1)

    }

    console.log(fn(3));
    //The fake input is 3
   /* return 3*fn(2)
    return 3*fn(2*fn(1))
    return 3*(2*1)
    return 3*2
    return 6 */
</script>
</html>

JavaScript advanced (3)

Using recursive function to find Fibonacci sequence (rabbit sequence) 1, 1, 2, 3, 5, 8, 13, 21

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
<script>
    //Using recursive function to find Fibonacci sequence (rabbit sequence) 1, 1, 2, 3, 5, 8, 13, 21
    //The user can input a number n to get the rabbit sequence value corresponding to this number
    //We only need to know the first two terms (n-1, n-2) of the user input n to calculate the corresponding sequence value of n
    function fb(n) {
        if (n === 1 || n === 2) {
            return 1;
        }
        return fb(n - 1) + fb(n - 2);
    }
    console.log(fb(3));
    console.log(fb(6));

  
</script>
</body>

</html>

JavaScript advanced (3)

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]