箭头函数的使用和this的指向

209 阅读1分钟

箭头函数的使用和this的指向

箭头函数的使用

<!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>

    <body>

        <script>
            // 箭头函数:也是定义函数的一种方式
            // const ccc = (参数列表) => {}
            const ccc = () => {

            }

            // 1. 参数问题
            const sum = (num1, num2) => {
                return num1 + num2;
            }

            // 2. 放入一个参数
            const power = num => {
                return num * num;
            }

            // 3. 函数中多行代码时
            const test = () => {
                console.log('hello');
                console.log('world');
            }

            // 4. 函数中只有一行代码
            const mul = (num1, num2) => num1 * num2;
        </script>
    </body>

</html>

箭头函数中this的指向

<!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>

    <body>
        <script>
            // 1. 什么时候使用箭头函数
            // setTimeout(function() {

            // }, 1000)

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


            // 结论: 箭头函数中的this如何查找?
            // 向外层作用域中,一层一层查找this,直到有this的定义
            const obj = {
                aaa() {
                    setTimeout(function() {
                        console.log(this); //window
                    })

                    setTimeout(() => {
                        console.log(this); // obj对象
                    })
                }
            }


            // 往外找到时候,有function就停下,然后用这个方法的this,匿名函数的就是window
            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); // obj对象
                        })
                    })
                }
            }
        </script>
    </body>

</html>