1.一般函数的this一般指向当前对象
var student={
name:"marry",
age:18,
eat:function(){
console.log(this)
console.log(this.name+"正在吃饭")
setTimeout(function(){
console.log(this)
})
}
}
student.eat()
输出结果如下:
定时器是异步操作,执行的时候,已经不指向当前的student对象了,指向的是执行的时候,所在的环境,所以输出的是window对象。
2.箭头函数的this,指向的是定义的时候所在的对象,不是使用的时候所在的对象
再如下代码段,将定时器里的函数调整为箭头函数:
var student={
name:"marry",
age:18,
eat:function(){
console.log(this)
console.log(this.name+"正在吃饭")
setTimeout(()=>{
console.log(this)
})
}
}
student.eat()
输出结果为:
改为箭头函数后,this的指向发生了变化,不再指向window对象,而是定义时所在的对象
若是将eat函数再调整为箭头函数:
var student={
name:"marry",
age:18,
eat:()=>{
console.log(this)
console.log(this.name+"正在吃饭")
setTimeout(()=>{
console.log(this)
})
}
}
student.eat()
输出结果如下,均指向了window对象
3.给元素对象绑定事件处理函数的时候,this指向当前触发事件的元素对象
<body>
<ol>
<li>索引下标0</li>
<li>索引下标1</li>
<li>索引下标2</li>
<li>索引下标3</li>
<li>索引下标4</li>
</ol>
</body>
<script type="text/javascript">
var lis=document.getElementsByTagName("ol")[0].getElementsByTagName("li");
lis=Array.from(lis);
lis.forEach(function(li,index){
li.onclick=function(){
this.style.backgroundColor="pink"
console.log(this)
}
})
</script>
当点击li对应输出该元素对象: