箭头函数

声明特点
1.this是静态的,this始终指向函数声明时所在作用域下的this的值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function getName(){
console.log(this.name);
}
let getName2=() => {
console.log(this.name);
}

window.name="小明";
const person={
name:"小红";
}

//直接调用
//getName(); //小明
//getName2(); //小明

//call方法调用
getName.call(person); //小红
getName2.call(person); //小明
2.不能作为构造实例化对象
1
2
3
4
5
6
let person=(name,age) =>{
this.name=name;
this.age=age;
}
let me=new Person('xiao',30);
console.log(me); //person is not a constructor
3.不能使用arguments变量
1
2
3
4
let fn = () = >{
console.log(arguments);
}
fn(1,2,3); //arguments is not defined
4.箭头函数的简写
    1.省略小括号,当形参有且只有一个的时候
    let add = n =>{
        return n+n;
    } 
    console.log(add(9));
    2.省略花括号,当代码体只有一条语句的时候,此时return必须省略,而且语句的执行结果就是函数的返回值
    let pow = n => n*n;
    console.log(pow(9));
箭头函数的实践和应用场景
需求1:点击div 2s后变为【粉色】
1
2
3
4
5
6
7
8
9
10
11
12
let ad=document.getElementById('ad');
//绑定事件
ad.addEventListener("click",function(){
//保存this的值
//let _this=this;往常的做法
setTimeout(() => {
//修改背景颜色
//console.log(this);
//_this.style.background='pink';
this.style.background='pink';
},2000);
});
需求2:从数组中返回偶数的元素
1
2
3
4
5
6
7
8
9
10
11
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);*/
const result=arr.filter(item => item%2 ===0)
箭头函数适合与this无关的回调,定时器,数组的方法回调
箭头函数不适合与this有关的回调,事件回调,对象的方法

箭头函数
https://blog-theta-ten.vercel.app/2021/06/13/箭头函数/
作者
Chen
发布于
2021年6月13日
许可协议