ES6之箭头函数

92 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>箭头函数</title>
</head>

<body>
    <button id="btn">点我一下</button>
    <script>
        // 因为现在的浏览器版本较高,所以都支持es6的箭头函数

        //一般定义函数的方式
        function fn1() {
            return 123
        }
        let a = fn1();
        console.log(a);


        //es6方法 fn是函数名字,没有参数直接就使用()  =>表示return
        let fn2 = () => 123;
        let b = fn2();
        console.log(b);

        //箭头函数一个参数可以省略括号“()”
        let fn3 = arg => arg; //加括号就是let fn = (arg) => arg;
        let c = fn3(123);
        console.log(c);

        //函数体里面有多个表达式,=>不表示返回,需要自己在大括号{}里面写return
        let fn4 = (a, b) => {
            let str = a + b;
            return str
        };

        // 箭头函数不可以作为构造函数
        let obj = new fn5(); //系统会报错“fn5()没有构造函数”


        let a = fn6('小明', '18');
        console.log(a);
        document.getElementById('btn').onclick = function() {
            console.log('外面的this', this) //this代表这个button
            setTimeout(function() {
                console.log('里面的this', this) //this代表window
            }, 1000)
        }

        document.getElementById('btn').onclick = function() {
            console.log('外面的this', this) //this代表这个button
            let that = this; //this代表这个button,用that指向他,以便setTimeout函数使用它
            setTimeout(function() {
                console.log('里面的this', that) //this代表这个button
            }, 1000)
        }

        document.getElementById('btn').onclick = function() {
            console.log('外面的this', this) //this代表这个button

            //箭头函数没有自己的this,setTimeout函数的this指的是上下文的this
            setTimeout(() => { //没有参数就直接写括号()
                console.log('里面的this', this) //this代表这个button
            }, 1000)
        }
    </script>
</body>

</html>