setTimeout 與 setInterval 中的 this
不管當前使用的this指向誰,在使用 setTimeout 或者 setInterval 中的 this 都會指向最外層對象,也就是window ,而使用箭頭函數就可以讓 this 繼續指向上一層對象而不是最外層。
<body>
<buttn id='demo'>發送驗證碼</button>
</body>
<script type="text/javascript">
// jquery
// 重新發送驗證碼倒計時
$("#demo").click(functuin() {
// 給demo按鈕添加disabled禁用屬性,this指向button標籤對象
$(this).addClass('disabled');
var time = 30;
// 想要在click中使用setTimeout, 普通寫法setTimeout(function(){}, 1000),會讓this指向window,導致不能使用$(this)去直接操作button
// 可以使用 _this = this 先把button對象拿出來,更簡單的方法是使用箭頭函數 (=>)
var interval= setInterval(() => {
if(condition){
// 去除定時器
clearInterval(interval);
$(this).removeClass('disabled');
$(this).attr('disabled', false);
$(this).test("重新發送");
return;
}
time--;
$(this).text('重新發送(' + time + 's)');
}, 1000)
})
</script>