410 ES6箭头函数

时间:2020-03-24
本文章向大家介绍410 ES6箭头函数,主要包括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);
        }, 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() {
            this.obj = {
                showThis: () => {
                    console.log(this); // Person
                }
            }
        }
        let fun5 = new Person();
        fun5.obj.showThis();
    </script>

</body>

</html>

原文地址:https://www.cnblogs.com/jianjie/p/12561817.html