this 关键字
每个函数内容都有一个关键字叫做this。不同的情况下,this代表的内容也是不一样的。
-
普通函数中的this代表window对象
function fn(){ console.log(this); } fn(); // window
-
定时器中的this代表window
var obj = { eat:function(){ setTimeout(function(){ console.log(this); }); } }; obj.eat(); // window
-
自调用函数中的this代表window
document.querySelector("button").onclick=function(){ (function(){ console.log(this); })() } // window
-
对象方法中的this代表调用这个方法的对象
var obj = { eat:function(){ console.log(this); } }; obj.eat(); // obj
-
事件函数中的this代表当前事件的事件源
document.querySelector("button").onclick=function(){ console.log(this); } // <button>按钮</button>
-
箭头函数的this在定义箭头函数的时候就知道了,代表上一行代码的this
document.querySelector("button").onclick=function(){ // 这里的this代表button按钮,所以箭头函数的this也是button按钮 setTimeout(()=>{console.log(this);}); } // <button>按钮</button>
重点:函数内部的 this 只和函数的调用方式有关系,和函数的定义方式没有关系。箭头函数在定义的时候就知道this代表什么