首页 > 在回调函数中如果使用箭头函数怎么获取相应的this?

在回调函数中如果使用箭头函数怎么获取相应的this?

举个例子,用jQuery

$('#test').on('click', ()=>{
    console.log(this) // window
});

那我要怎么获取外部和内部的this?除了将箭头函数换成原来的function就没有其他方法了吗?


阮一峰es6中说到,箭头函数中没有自己的this:

this指向的固定化,并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this

官方也有说明:

Arrow functions capture the this value of the enclosing context

所有箭头函数通过call或者apply调用时传this也是没有效果的


在我理解来看,箭头函数是在想保留当前this的引用而用的。

简单举例:

document.body.addEventListener('click',function(){
    // 想在1s后改变一下背景色
    
    // 错误示范
    setTimeout(function(){
        // 如果使用匿名函数的话,this就不再指向body元素了
        this.style.backgroundColor = 'red';
    },1000);
    
    // 所以为了保留原来this的引用,我应该用箭头函数

    // 正确写法
    setTimeout(()=>{
        // 这时候this还是指向body
        this.style.backgroundColor = 'red';
    },1000); 
});

所以啊,绑定事件什么的,就用匿名函数吧。

【热门文章】
【热门文章】