一、什么是箭头函数
所谓箭头函数,如其名,就是带箭头的函数,能够定义匿名函数。
用箭头函数之前我们的基础写法:
let fun = function () {
console.log('fun()');
};
fun();
我们用箭头函数这样写:
let fun1 = () => console.log('我是箭头函数');
fun1();
//声明一个函数
let fn = (a,b) => {
return a + b;
}
//调用函数
let result = fn(1, 2);
console.log(result);
二、箭头函数 形参的情况
1. 没有形参,并且函数体只有一条语句,()可以省略
//1.没有形参,并且函数体只有一条语句,()可以省略
let fun1 = () => console.log('我是箭头函数');
fun1();
2. 一个形参,()可以省略
let fun2 = x => x;
console.log(fun2(5));
3. 两个及两个以上的形参,()不能省略
let fun3 = (x, y) => x + y;
console.log(fun3(25, 39));
打印结果:
三、箭头函数 函数体情况
1. 函数体只有一条语句或者是表达式的时候,{}可以省略。此时 return 必须省略,而且语句的执行结果就是函数的返回值。
let fun4 = (x,y) => x + y;
console.log(fun4(20, 40));//60
2. 函数体不止一条语句或者是表达式的情况,{}不可省略。
let fun5 = (x, y) => {
console.log(x, y);//34 38
return x + y;
};
console.log(fun5(34, 48));//82
打印结果:
四、箭头函数 this的指向
箭头函数没有自己的this,箭头函数的this不是调用的时候决定的,而是在定义的时候处在的对象就是它的this。
扩展理解: 箭头函数的this看外层的是否有函数,如果有,外层函数的this就是内部箭头函数的this,如果没有,则this是window。
1. 没有箭头函数时
let btn = document.getElementById('btn');
//没有箭头函数
btn.onclick = function () {
console.log(this);//btn
};
2. 箭头函数
//箭头函数
let btn2 = document.getElementById('btn2');
let obj = {
name : 'kobe',
age : 39,
getName : () => {
btn2.onclick = () => {
console.log(this);
};
}
};
obj.getName();//window
五、箭头函数基本特点
1、this 是静态的,this 始终指向函数声明时所在作用域下的 this 的值(也可看第四部分内容)
function getName(){
console.log(this.name);
}
let getName2 = () => {
console.log(this.name);
}
//设置 window 对象的 name 属性
window.name = '尚硅谷';
const school = {
name: "ATGUIGU"
}
//直接调用
getName();
getName2();
console.log("----------------");
//call 方法调用
getName.call(school);
getName2.call(school);
2、不能作为构造实例化对象
let Person = (name, age) => {
this.name = name;
this.age = age;
}
let me = new Person('xiao',30);
console.log(me);
3、不能使用 arguments 变量
let fn = () => {
console.log(arguments);
}
fn(1,2,3);
六、箭头函数实践
1、点击 div 2s 后颜色变成『粉色』
HTML代码:
<div id="ad"></div>
CSS代码:
div {
width: 200px;
height: 200px;
background: #58a;
}
JS代码:
以往写法:
//获取元素
let ad = document.getElementById('ad');
//绑定事件
ad.addEventListener("click", function(){
//保存 this 的值
let _this = this;
//定时器
setTimeout(() => {
//修改背景颜色 this
_this.style.background = 'pink';
}, 2000);
});
使用ES6箭头函数写法:
//获取元素
let ad = document.getElementById('ad');
//绑定事件
ad.addEventListener("click", function(){
//定时器
setTimeout(() => {
//修改背景颜色 this
this.style.background = 'pink';
}, 2000);
});
2、从数组中返回偶数的元素
以往写法:
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);
使用ES6箭头函数写法:
const arr = [1,6,9,10,100,25];
const result = arr.filter(item => item % 2 === 0);
console.log(result);