特别简单的一个html结构
<div class="test">
</div>
测试需求为点击显示this指向
- 直接在标签中调用
<div class="test1" onclick="t();">
</div>
function t(){
console.log(this);
}
浏览器控制台结果
在这种情况下,相当于告诉浏览器去找到t函数,然后执行它,t函数在全局对象空间中,所以this指向window
2. 普通匿名函数
var test = document.querySelector('.test');
test.addEventListener('click',function(event){
console.log(this);
});
浏览器控制台结果
3. 箭头函数
var test = document.querySelector('.test');
test.addEventListener('click',()=>{
console.log(this);
});
浏览器控制台结果
分析
普通的匿名函数中this指向触发事件的元素
箭头函数由于不会创建自己的this,它只能从作用域链的上层继承this,所以this指向全局对象window
参考资料:https://www.quirksmode.org/js/this.html
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%AD%E7%9A%84_this
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arrow_functions#%E5%83%8F%E6%96%B9%E6%B3%95%E4%B8%80%E6%A0%B7%E4%BD%BF%E7%94%A8%E7%AE%AD%E5%A4%B4%E5%87%BD%E6%95%B0