箭头函数

161 阅读3分钟

箭头函数

(1)箭头函数定义

ES6允许使用箭头(=>)定义函数,箭头函数提供了一种更加简洁的函数书写方式,箭头函数多用于匿名函数的定义;基本语法是:

参数 => 函数体 //当参数只有一个时可以去掉括号,函数体可以直接是返回值return,可以不加大括号
(参数) => {函数体} //在开发项目中我还是习惯加括号和大括号,增加可读性。
(2)箭头函数特点

基本语法:

//普通函数
var f = function(a){
 return a;
}
f(1);  //1//箭头函数
var f = a => a
f(10); //10

当箭头函数没有参数或者有多个参数,要用 () 括起来。

var f = (a,b) => a+b;
f(6,2);  //8

当箭头函数函数体有多行语句,用 {} 包裹起来,表示代码块,当只有一行语句,并且需要返回结果时,可以省略 {} , 结果会自动返回。

var f = (a,b) => {
 let result = a+b;
 return result;
}
f(6,2);  // 8

当箭头函数要返回对象的时候,为了区分于代码块,要用 () 将对象包裹起来

var f = (id,name) => ({id: id, name: name});
f(6,2);  // {id: 6, name: 2}

注意点:没有 this、super、arguments 和 new.target 绑定。

var a = () => {
    // 箭头函数里面没有 this 对象,
    // 此时的 this 是外层的 this 对象,即 Window 
    console.log(this);
}
a(11);
​
var b = () => {
    console.log(arguments);
}
b(111); // ReferenceError: arguments is not defined

对象中使用箭头函数,this表示全局Window对象

var obj = {
    name: "xx",
    show: function() {
        console.log(this); //this表示当前对象
    },
    say: () => {
        console.log(this); //this表示全局window对象
    }
}

箭头函数体中的 this 对象,是定义函数时的对象,而不是使用函数时的对象。

function a() {
    setTimeout(function() {
        console.log(this); //this始终指向全局Window对象
    }, 100)
}
a.call({num: 200});
                    
function b() {
    setTimeout(() => {
        console.log(this); //this绑定的是b函数中的this对象
    }, 100);
}
b.call({num: 300});

注意:箭头函数不可以作为构造函数,也就是不能使用 new 命令,否则会报错

function Person() {
    console.log(this);
}
new Person(); //Person {}
            
var People = ()=>{
    console.log(this);
}
new People(); //TypeError: People is not a constructor

箭头函数在参数中使用

var arr= [1,2,3];
arr = arr.map((a)=>a*a);
console.log(arr);

箭头函数可以与解构一起使用

//变量为目标,返回值为源
let cal = (a, b) => {
    return {
        add: a+b,
        sub: a-b,
        mul: a*b,
        div: a/b
    };
}
let {add, sub, mul, div} = cal(10, 5);
​
//形参为目标,实参为源
var show = ({one, two}) => {
    console.log(one + "---" + two);
}
show({one: "hello", two: "你好"});

解决箭头函数中没有arguments 绑定的问题?

var show = (a, b, ...reset) => { //...reset接收剩余参数,组成新数组。
    console.log(a + b);
    console.log(reset);
}
show(1, 2, 3, 4, 5);

箭头函数不可以使用call、bind、apply改变this指向问题

    let obj={name:"mya"}
    let fn=()=>{console.log(this);}.bind(obj);//报错
(2)适合使用的场景

ES6 之前,JavaScript 的 this 对象一直很令人头大,回调函数,经常看到 var self = this 这样的代码,为了将外部 this 传递到回调函数中,那么有了箭头函数,就不需要这样做了,直接使用 this 就行。

所以,当我们需要维护一个 this 上下文的时候,就可以使用箭头函数。

(3)总结
  • 要有个箭头
  • 箭头的前面是小括号,放形参,只有一个形参的时候可以省略小括号;
  • 箭头的后面是函数体;
  • 如果函数体只有一个语句,没有{},此时的返回值不需要return;
  • 箭头函数里面的this总是指向最靠近的function 内部的this;
  • 对象里面的方法,尽可能不要使用箭头函数;
  • 箭头函数里面没有arguments,可以使用…reset,接收过来就是数组类型,接收的是形参之外的所有的实参;
  • 箭头函数不可以使用call、bind、apply改变this指向问题