【ES6系列】 - 箭头函数

90 阅读1分钟

基本语法

这是ES5的函数写法:

    function test(a, b){ 
        return a + b;
    }

这是ES6的箭头函数写法:

 var test = () => {} 
 var test2 = (a, b) => return a + b //两个变量的写法,如果只有一个函数执行语句可以省略大括号
 var test3 = (a, b) => ({x: a + b}) // 返回一个对象的写法

特点与区别

1、箭头函数没有自己的this,只能通过父级的this来获取this。

2、箭头函数不能作为构造函数使用,不能通过call, bind, apply来改变this指向

    var test = () => return 1;
    var t1 = new test();
    console.log(t1) //TypeError>> test is not a constructor

3、箭头函数没有arguments, 但是可以用rest运算符来替代(...)

    var test = (...arg) => {}

4、箭头函数没有原型

    var test = () => {}
    console.log(test.prototype); //undefined

5.箭头函数没有new.target

关于 new.target,可以参考 es6.ruanyifeng.com/#docs/class…


阮一峰箭头函数讲解:es6.ruanyifeng.com/?search=new…