DOM中原生函数和箭头函数中的this
<input type="button" value="点我" id="btn">
document.getElementById('btn').onclick = function() {
alert(this) // 当前点击的对象
}
document.getElementById('btn').onclick = () => {
alert(this) // window
}
因为箭头函数不会自动绑定局部变量,所以箭头函数没有自己的this,它的this是沿着作用域链继承来的,是离它最近的那个this
DOM中for循环和时间函数的优先级
<input type="button" value="123">
<input type="button" value="123">
<input type="button" value="123">
const btnObjs = document.getElementsByTagName('input')
for(var i=0; i<btnObjs.length; i++) {
btnObjs[i].onclick = function() {
alert(i) // 3
alert(this) // 当前点击的对象
}
}
不管点哪一个按钮,输出的都是3,为什么? 这是因为在页面加载完毕的时候for循环就已经执行完了,这时i的值就是 btnObjs.length 不再是我们点击的当前按钮的那个下标了,所以这个时候要用this代替下标