7.箭头函数的实践
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
background: #56a;
}
</style>
</head>
<body>
<div id="d1"></div>
<script>
let d1 = document.getElementById("d1");
d1.addEventListener("click", function () {
//这里不能用箭头函数,需要this指向当前的d1元素,而写了箭头函数this会指向window
// 保存this的值
// _this = this;
// setTimeout(function () {
// _this.style.background = "pink"; //之前的写法,因为this在这里指向window,所以要提前保存this的值
// }, 3000);
// setTimeout(() => {
// this.style.background = "pink"; //箭头函数写法,this指向外部定义的地方
// }, 300);
});
let arr = [1, 2, 3, 4, 5, 6, 7];
let result = arr.filter((item) => item % 2 === 0);
console.log(result);
// 箭头函数适合与this无关的回调:定时器,数组的方法回调
// 箭头函数不适合与this有关的回调,事件回调,对象的方法
</script>
</body>
</html>
浙公网安备 33010602011771号