箭头函数

73 阅读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>Document</title>
</head>

<body>
    <button id="dian">点我一下</button>
    <script>
        /* 因为现在的浏览器都是高版本的所以直接支持es6语法 */
        /* function fn() {
            return arguments[0]
        } */
        /* let a = fn(); */

        /* fn函数名 没有参数直接() => 表示return */
        /* let fn = () => 123; */

        /* 箭头函数里面没有arguments */
        /* let fn = () => arguments; */

        /* 箭头函数里面一个参数可以省略() */
        /* let fn = arg => arg; */

        /* 箭头函数里面多个参数不可以省略() */
        /* let fn = (a, b) => a + b; */

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

        /* fn is not a constructor  箭头函数不可以作为构造函数使用 */
        /* let obj = new fn();
        console.log(obj); */

        /* let a = fn('龚助', '没有了助');
        console.log(a); */

        document.getElementById('dian').onclick = function () {
            console.log('外面的this', this)/* button */
            /* let that = this; */
            /* 箭头函数没有自己的this this是上下文的(代表是外面的this) */
            /*  箭头函数没有参数要加() */
            setTimeout(() => {
                /*  console.log('普通函数里面的this',this) */ /* window */
                /*  console.log('里面的that',that) */  /* button */
                console.log('箭头函数里面的this',this)
            }, 1000)
        }
    </script>
</body>

</html>