The use of arrow functions and the pointing of this

The use of arrow functions

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

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <title>Document</title>
    </head>

    <body>

        <script>
            // Arrow function: is also a way to define functions
            // const CCC = (parameter list) => {}
            const ccc = () = >{}// 1. Parameter problem
            const sum = (num1, num2) = > {
                return num1 + num2;
            }

            // 2. Add a parameter
            const power = num= > {
                return num * num;
            }

            // 3. Multiple lines of code in a function
            const test = () = > {
                console.log('hello');
                console.log('world');
            }

            // 4. There is only one line in the function
            const mul = (num1, num2) = > num1 * num2;
        </script>
    </body>

</html>
Copy the code

The arrow function refers to this

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

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <title>Document</title>
    </head>

    <body>
        <script>
            // 1. When to use the arrow function
            // setTimeout(function() {

            // }, 1000)

            setTimeout(() = > {
                console.log(this); // window
            }, 1000);


            // Conclusion: how to find this in arrow function?
            // Look for this layer by layer in the outer scope until you have a definition of this
            const obj = {
                aaa() {
                    setTimeout(function() {
                        console.log(this); //window
                    })

                    setTimeout(() = > {
                        console.log(this); / / object obj}}})// If this function is found, stop it and use this method
            const obj2 = {
                aaa() {
                    setTimeout(function() {
                        setTimeout(function() {
                            console.log(this); // window
                        })

                        setTimeout(() = > {
                            console.log(this); // window})})setTimeout(() = > {
                        setTimeout(function() {
                            console.log(this); // window
                        })

                        setTimeout(() = > {
                            console.log(this); / / object obj}}})})</script>
    </body>

</html>
Copy the code