ES6 允许使用 “箭头” (=>)定义函数。

1、基本用法

(1)如果箭头函数不需要参数或需要多个参数,就使用一个圆括号代表参数部分

var f = () => 5;
//等同于
var f = function () {
    return 5
};

var sum = (num1, num2) =>  num1 + num2;
//等同于
var sum = function(num1, num2){
    return num1 + num2;
}

(2)如果箭头函数的代码块部分多于一条语句,就要使用大括号将它们括起来,并且使用 return 语句返回。

var sum = (num1,num2) => {
  let total = num1+ num2;
  return total; 
}

(3)由于大括号会被解释为代码块,所以如果箭头函数直接返回一个对象,就必须在对象外面加上括号,否则会报错。

// 报错
let getTempItem = id => { id: id, name: "Temp" };

// 不报错
let getTempItem = id => ({ id: id, name: "Temp" });
getTempItem(1);//{id: 1, name: "Temp"}

2、箭头函数与变量解构结合使用

const full = ({ first, last }) => first + ' ' + last;
full({first: 1, last: 2});// "1 2"

// 等同于
function full(person) {
  return person.first + ' ' + person.last;
}
full({first: 1, last: 2});// "1 2"

3、rest 参数与箭头函数结合

const numbers = (...nums) => nums;
numbers(1,2,3,4);//  [1, 2, 3, 4]

const headAndTail = (head, ...tail) => [head, tail];
headAndTail(1,2,3,4);// [1,[2,3,4]]

4、箭头函数与普通函数的区别

总结如下:

1、箭头函数没有 prototype(原型对象)
2、this 指向规则不同,
箭头函数里的this是定义的时候决定的,
普通函数里的this是使用的时候决定的
3、箭头函数不能作为构造函数
4、箭头函数不绑定arguments,取而代之用 rest 参数 …x 解决
5、箭头函数不能当做 生成器Generator 函数,不能使用 yield 关键字

4.1、箭头函数没有 prototype(原型对象)
function test1 () {
	console.log(test1.prototype)
}
test1()           // constructor: f test1()
var test2 = () => {
	console.log(test2.prototype)
}
test2()       //  undefined;
4.2、this 指向规则不同
  • 箭头函数
    1、由于它没有 prototype(原型),所以它本身没有 this
    2、任何方法都改变不了this指向,箭头函数没有this,所以并没有 call(),bind(),apply() 方法。
    3、但是可以通过改变它外层 this 指向来间接的改变。
    4、箭头函数中的this指向的是定义时的this,而不是执行时的this,想一想vue框架中的this,永远指向的是当前组件的实例
var obj = {
   x:100, //属性x
   show1(){
        setTimeout(
            // 匿名函数: 此时的this已经是window了
           function(){console.log(this.x);},  500 );      // undefined
    },
   show2(){
        setTimeout(
            // 箭头函数: 此时的this是对象定义时的this
           () =>{console.log(this.x);},  500 );      // 100
    }
};
obj.show();//打印结果:undefined
  • 普通函数 :
    this 指向调用它的那个对象,可以使用 call(),bind(),apply() 等方法重新指定 this 的指向。
4.3、箭头函数不能作为构造函数

由于箭头函数是匿名函数,且没有this,因此不能作为构造函数,不能使用new

let test3 = () => {
    console.log(this)  
 }
 let test4 = new test3()    /* 报错: Uncaught TypeError: test3 is not a constructor*/
4.4、箭头函数不绑定arguments,取而代之用 rest 参数 …x 解决
function A () {
    console.log(arguments)         //1,2,3,4
  }
A(1,2,3,4);
	  
const B = (...b) => {
    console.log(b)                //5,6,7,8
  };
B(5,6,7,8);
 
const C = (c) => {
    console.log(arguments)// 报错:Uncaught ReferenceError:arguments is not defined
  };
C(9,10,11,12);
4.5、箭头函数不能当做 生成器Generator 函数,不能使用 yield 关键字
4.6、箭头函数不支持重命名函数参数,普通函数的函数参数支持重命名
function func1(a, a) {
  console.log(a, arguments); // 2 [1,2]
}

var func2 = (a,a) => {
  console.log(a); // 报错:在此上下文中不允许重复参数名称
};
func1(1, 2); func2(1, 2);
4.7、箭头函数在参数和箭头之间不能换行!

typescript 箭头函数泛型 箭头函数有prototype_es6