410 ES6箭头函数

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

<head>
    <meta charset="UTF-8">
    <title>06_箭头函数</title>

</head>

<body>
    <button id="btn">测试箭头函数this_1</button>
    <button id="btn2">测试箭头函数this_2</button>


    <!--
        * 作用: 定义匿名函数
        * 基本语法:
        * 没有参数: () => console.log('xxxx')
        * 一个参数: i => i+2
        * 大于一个参数: (i,j) => i+j
        * 函数体不用大括号: 默认返回结果
        * 函数体如果有多个语句, 需要用{}包围,若有需要返回的内容,需要手动返回
        * 使用场景: 多用来定义回调函数

        * 箭头函数的特点:
            1、简洁
            2、箭头函数没有自己的this,箭头函数的this不是调用的时候决定的,而是在定义的时候处在的对象就是它的this
            3、扩展理解: 箭头函数的this看外层的是否有函数,
                         如果有,外层函数的this就是内部箭头函数的this,
                         如果没有,则this是window。
    -->

    <script type="text/javascript">
        let fun = function() {
            console.log('fun()');
        };
        fun();

        // 没有形参,并且函数体只有一条语句
        let fun1 = () => console.log('fun1()');
        fun1();
        console.log(fun1());

        // 一个形参,并且函数体只有一条语句
        let fun2 = x => x;
        console.log(fun2(5));

        // 形参是一个以上
        let fun3 = (x, y) => x + y;
        console.log(fun3(25, 39)); // 64

        // 函数体有多条语句
        let fun4 = (x, y) => {
            console.log(x, y);
            return x + y;
        };
        console.log(fun4(34, 48)); // 82

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

        let btn = document.getElementById('btn');
        // 没有箭头函数
        btn.onclick = function() {
            console.log(this); // btn
        };

        // 箭头函数
        let btn2 = document.getElementById('btn2');

        let obj = {
            name: 'kobe',
            age: 39,
            getName: () => {
                btn2.onclick = () => {
                    console.log(this); // Window
                };
            }
        };
        obj.getName();


        function Person(name) {
            this.name = name,
            this.obj = {
                showThis: () => {
                    // Person {name: "刘德华", obj: {…}},因为这个箭头函数showThis的外面有函数Person
                    console.log(this); 
                }
            }
        }
        let fun5 = new Person('刘德华');
        fun5.obj.showThis();
    </script>

</body>

</html>

posted on 2020-03-24 20:52  冲啊!  阅读(110)  评论(0编辑  收藏  举报

导航