一、绑定dom事件处理函数
利用箭头函数,将原本的this传递给事件处理函数。
var handler = {id: '123456',init: function() {document.addEventListener('click',event => this.doSomething(event.type), false);//绑定事件处理函数的方法中,回调函数使用箭头函数,//箭头函数中,通过this来调用真正事件处理函数,实现对普通函数this的绑定},doSomething: function(type) {console.log('Handling ' + type + ' for ' + this.id);}//为什么事件处理函数不能用箭头函数,因为定义的时候this就确定了,//如果是箭头函数的话,this指向外层作用域的this -> window};
二、箭头函数中,this指向
箭头函数中,没有自己this对象,this是固定的,是在定义时已经绑定。外层作用域的this,如果外层函数没有自己this,再往外部寻找,直至找到全局上下文(全局上下文中,this不论是否为严格模式,都指向window)。箭头函数不是通过function关键字创造的,所以跟普通函数存在区别(argumetns、new关键字、this等区别)。
let function test (){return ()=>{return ()=>{return ()=>{console.log('id' + this.id)}}}}let foo = test.call({id:123}),foo1 = foo.call({id: 5})()(),foo2 = foo().call({id:6})(),foo3 = foo()().call({id:8});foo1() // => 123foo2() // => 123foo3() // => 123
三、arguments,箭头函数没有自己的arguments,但是可以往外层作用域查找该属性
function test(){console.log(arguments)setTimeout(()=>{console.log(arguments)},100)// 两个arguments为同一个对象}test(1,2,3)
四、使用场景
(1)回调函数的简写
let a = [1,2,3,4,5,6],arr = a.reduceRight((accumulator,elem)=>{accumulator[elem] = elemreturn accumulator},{})
(2)面向对象中绑定事件函数时,替换bind操作(见部分一)
五、不适用场景
(1)递归函数
(2)构造函数,不能用new
(3)事件处理函数
(4)不能用作vue的methods的方法
