首先必须记住!!!定时器(setTimeout、setIntervel)里直接用this,会指向window(后面有法子解决这个问题)!!!
this永远跟着函数走,哪怕是setTimeout也是如此,下面举个实例助于理解:
setTimeout(function(){
console.log(this);
}, 2000);
注意到this外面有个function,这可是大坑。
把这个运用到实例中可以看到:
<script>
let oBtn=document.getElementById('btn1');
oBtn.onclick=function(){
console.log(this);//输出<button></button>
setTimeout(function(){
console.log(this);//输出window
}, 2000);
};
</script>
当setTimeout里的this最近一层已经有了一个function,所以oBtn.οnclick=function()的这个function就不起作用了。
那问题大家都知道,如何解决?
方法一: 不用this,惹不起我躲得起!
<script>
let oBtn=document.getElementById('btn1');
oBtn.onclick=function(){
//console.log(this);//输出<button></button>
setTimeout(function(){
console.log(oBtn);//直接用oBtn代替this,爽快
}, 2000);
};
</script>
方法二:涉及到es6中的箭头函数。(所以es6用起来)
<script>
let oBtn=document.getElementById('btn1');
oBtn.onclick=function(){
console.log(this);//输出<button></button>
setTimeout(()=>{
console.log(this);//输出oBtn
}, 2000);
};
</script>