this是一个在作用域内的关键字
指向
全局使用:this -> window
console.log(this); // Window
普通调用:this -> window
function fn() { console.log(this); } // Window fn();
对象调用:this -> .前的对象
function fn() { console.log(this); // {fun: ƒ} 即 obj } var obj = { fun: fn } obj.fun();
定时器处理函数:this -> window
setTimeout(fn, 0) // Window setTimeout(obj.fun, 0) // Window
事件处理函数:this -> 事件源
<div id="btn">this指向</div>
var btn = document.getElementById('btn'); btn.onclick = fn; // dom: <div id="btn">this指向</div> btn.onclick = obj.fun; // dom: <div id="btn">this指向</div>
自执行函数:this -> window
!function () {console.log(this)} () // Window
需要强调的一点是:this指向只看调用方式,例:
var btn = document.getElementById('btn')
btn.onclick = function(){
console.log(this);
function fn() {
console.log(this);
}
var obj = {
fun: fn
}
fn();
obj.fun();
};
// <div id="btn">this指向</div>
// Window {window: Window, self: Window, document: document, name: '', location: Location, …}
// {fun: ƒ}