JavaScript的普通函数,箭头函数作用域的区别
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#ad {
width: 200px;
height: 200px;
background: #58a;
}
</style>
</head>
<body>
<div id="ad"></div>
</body> <script>
let ad = document.getElementById('ad')
ad.addEventListener("click", function () {
console.log(this);
let _this = this
//普通函数,谁调用,this就指向谁,
//setTimeout 调用回调函数,则里面的this是window,因为window.setTimeout
setTimeout(function(){
console.log('普通匿名函数this的指向', this)
_this.style.background = 'pink';
}, 2000)
})
ad.addEventListener("dblclick",function(){
console.log(' 双击鼠标');
//箭头函数的在定义时就已经指定好this的指向,指向了父作用域
//所以setTimeout的回调箭头函数指向了 父级function()
setTimeout(()=>{
console.log(this)
this.style.background = 'blue';
}, 2000)
})
</script>
只是查找方便的总结