结论:谁调用this,this就指向谁
1.对象中的this指向对象
2.全局函数中的this指向window
3.事件回调函数
3.1.行内绑定传参的this指向window
3.2.行内绑定不传参的this指向本身
3.3.动态绑定的this指向当前节点
4.构造函数调用模式 this —> 创建出来的实例 new 函数名()
5.箭头函数中this没有明确指向,会向上一级(宿主对象)寻找
6.定时器中的this指向window
// 1.对象:指向对象本身
var obj={say(){console.log(this);}}
obj.say();//{ say: ƒ}
//2.全局函数:指向window
function f(){console.log(this);}
f();//window
</script>
//3.定时器:指向window
/*因为setTimeout,setIntervar,location等都是window的子对象*/
setInterval(function(){console.log("666");},1000)//window
//4.箭头函数:指向宿主对象
var s1 = () => { console.log(this);}
s1();//window
//5.构造函数的this指向实例对象
function Person() {this.name = "zs";}
var p = new Person();
console.log(p.name);//zs
<!--6.事件回调函数中的this指向-->
<p onclick="f(this)">点击此处 </p>
<p id="pp">点击pp</p>
<script>
// 1.行内绑定:传参==>this指向节点本身(有直接调用者)
function f(params) {
console.log(params); //<p onclick="f(this)">点击此处 </p>
}
// 2.行内绑定:不传参==>this指向window(没有直接调用者)
function f() {
console.log(this); //window
}
// 3.动态绑定==>this指向节点本身
var pp = document.getElementById("pp");
pp.onclick = function() {
console.log(this); //<p id="pp">点击pp</p>
}
总结
this 总是指向函数的直接调⽤者(⽽⾮间接调⽤者)
如果有 new 关键字, this 指向 new 出来的那个对象
在事件中, this 指向触发这个事件的对象(特殊的是, IE 中的 attachEvent 中的this 总是指向全局对象 Window)