每个函数内容里都有一个关键字叫做this。不同的情况下,this代表的内容也是不一样的。
箭头函数没有this,箭头函数的this是它所处的上层环境的this。
普通函数可以通过事件、apply/call等改变this指向,但是和箭头函数通通没有关系。
function fn(){
console.log(this);
}
fn(); //this就是--> window
var obj = {
eat:function(){
setTimeout(function(){
console.log(this);
});
}
};
obj.eat(); // this就是-->window
document.querySelector("button").onclick=function(){
(function(){
console.log(this);
})()
}
// this就是-->window
注意:这里的this不是方法,不是方法,不是方法。
var obj = {
skill:function(){
console.log(this);
}
};
obj.skill(); // this就是-->obj
也就是说事件函数中,谁调用,this就指向谁。
document.querySelector("button").onclick=function(){
console.log(this);
}
//this就是--> <button>按钮</button>
箭头函数没有this,箭头函数的this是它所处的上层环境的this。在定时器内部定义了一个箭头函数,在这里没有自身的this指向,指向上层环境中的this,上层环境就是button按钮点击事件,所以这里的this就是button按钮。
document.querySelector("button").onclick=function(){
// 这里的this代表button按钮,也就是定时器内的箭头函数的上层环境,所以定时器内部的箭头函数的this就是button按钮
setTimeout(()=>{console.log(this);});
}
//this就是--> <button>按钮</button>