1024ES6JavaScript 进阶营

8.ES6箭头函数

2019-02-11  本文已影响2人  圆梦人生

ES6中函数的定义可以使用箭头( => ) 来定义:

1、函数可使用箭头定义 =>
2、当函数只有一个参数的时候 可以省略()
3、当函数只有一行代码时可以省略{}
4、箭头函数不绑定this(直接调用的this是继承父级的this)

案例


<html>
    <head>
        <title>箭头函数</title>
        <meta charset="utf-8"/>
        <script>
            
            // es5 函数定义
            var abc = function(){
                alert(1);
            }
            //
            abc(); // 1
            
            // es6 使用箭头函数定义
            var abc2 = ()=>{
                alert(2);
            }
            //
            abc2(); // 2
            
            // es6 当函数只有一个参数的时候 可以省略()
            var abc3 = n =>{
                alert(n * 2);
            }
            abc3(10)  // 20
            
            //  es6 当函数只有一行代码时可以省略{}
            var abc4 = n => alert(n * 2)
            abc4(20) // 40
            
            // 箭头函数不绑定this
            // es5 函数 this
            var abc5 = function(){
                //
                return {
                    aa: function(){
                        console.log(this); // this指向的是当前aa函数
                        this.abc && this.abc() // 当前aa函数下没有abc
                    }
                }
            }
            abc5().aa();
            // es6 箭头函数 this
            var abc6 = ()=>{
                //
                return {
                    aa:()=>{
                        console.log(this); // this指向的是当前window
                        this.abc && this.abc() // 调用abc函数 弹出1
                    }
                }
            }
            abc6().aa();
        </script>
    </head>
    <body>
        
    </body>
</html>

上一篇 下一篇

猜你喜欢

热点阅读