箭头函数实践
#箭头函数实践
<style>
div {
width:200px;
height:200px;
background:#baf;
}
</style>
<div id='ad'>
<script>
// 1、需求:点击 div 之后两秒颜色发生改变
//获取元素
let ad = document.getElementById('ad');
//绑定事件
ad.addEventListener("click",function(){
//设置一个定时器
// (使用 _this 保存此时 function 的this)
//(var _this = this;)
setTimeout(function(){
//修改背景颜色
//如果直接没有上边的 _this = this; 会报错,this 指向 window
// _this.style.background = 'pink';
},2000)
//但是可以使用就按头函数更加方便一点
setTiemOut(() => {
//修改背景颜色
this.style.background = 'pink';},2000)
})
</script>
</div>
这是因为在箭头函数下, this是静态的 其指向的是在声明时候的作用域。上述的箭头函数的 this 指向的是 function 。
function 的事件源是 ad 所以 箭头函数 里面的 this 就指向了 ad 本身。
需求二
从数组中返回偶数的元素
//使用原来的方法
const arr = [1,6,9,10,100,25];
const result = arr.filter(function( item ){
if(item % 2 ===0){
return true;
}else{
return false;
}
});
console.log(result);
// ===>arr[6,10,100]
//箭头函数的方法\1-1
const arr = [1,6,9,10,100,25];
const result = arr.filter((item) => {
if(item % 2 ===0){
return true;
}else{
return false;
}
});
console.log(result);
// ===>arr[6,10,100]
//箭头函数的方法\1-2--省略小括号
const arr = [1,6,9,10,100,25];
const result = arr.filter(item => {
if(item % 2 ===0){
return true;
}else{
return false;
}
});
console.log(result);
// ===>arr[6,10,100]
//箭头函数的方法\1-3 超级简化
const arr = [1,6,9,10,100,25];
const result = arr.filter(item => item % 2 ===0);
console.log(result);
// ===>arr[6,10,100]
说明filter函数
参数
item: 会将遍历数组中的每一个元素当作实参传递给 item
return
true: 条件判断为真时,直接返回当前遍历的数组的元素 即 item 的值,并添加到新的数组里面。
fales:条件判断为假时,不返回任何值,继续遍历数组。
**箭头函数合适与 this 无关的回调 **
- 定时器
- 数组的方法回调
箭头函数不适合与 this 有关的事件回调函数
-
DOM元素的事件回调函数,因为此时的 this 时指向事件源的;
-
对象的方法;
{
//对象的方法
name : ‘菜鸟’;
getName : function(){
this.name; //此时的 this 指向的是 对象的 name
}//使用箭头函数 getName :() => { this.name; //此时的 this 指向对象作用域以外的作用域 }
}