目的:引入箭头函数的目的是更简短的函数写法并且不绑定this,箭头函数的语法比函数表达式更简洁
一.基本语法
const fn=function() {
console.log(123);
}
const fn=(x)=>{
console.log(x);
}
fn(1);
1.只有一个形参的时候可以省略小括号
const fn = x => {
console.log(x);
}
fn(1);
2.只有一行代码时,我们可以省略大括号
const fn = x => console.log(x);
fn(1);
3.只有一行可以省略return
const fn=x=>x+x;
console.log(fn(1));
const fn=(x,y)=>x+y;
console.log(fn(1,2));
4.加括号的函数体返回对象字面量表达式
const fn=(uname)=>({uname:uname});
console.log( fn("刘德华"));
二.箭头函数参数
1.普通函数有argumegts 动态参数
2.箭头函数没有arguments 动态参数,但是有剩余参数..args
利用箭头函数来求和
const getSum=(...arr)=>{
let sum=0;
for(let i=0;i<arr.length;i++){
sum+=arr[i];
}
return sum;
}
const result= getSum(1,2,3);
console.log(result);
三.箭头函数中的this
1.普通函数
function fn(){
console.log(this);//window
}
fn();
2.对象方法里面的this
对象方法里面的this
const obj={
name :'andy',
sayHi:function(){
console.log(this);//obj
}
}
obj.sayHi();
箭头函数不会创建自己的this,它只会从自己的作用域链的上一层沿用this。
3.箭头函数里面的this
const fn = () => {
console.log(this);//window
}
fn();
4.对象方法箭头函数的this
const obj = {
name: 'andy',
sayHi: () => {
console.log(this);//window
}
}
obj.sayHi();
const obj = {
name: 'andy',
sayHi: function () {
let i = 10;
const count = () => {
console.log(this);//obj
}
}
}
obj.sayHi();
注意:在开发中【使用箭头函数前需要考虑函数中 this 的值,事件回调函数使用箭头函数时, this 为全局的 window,因此DOM事件回调函数为了简便。还是不太推荐使用箭头函数