002.ES2015和ES2016新特性--箭头函数.md

1. ES2015中的箭头函数

JavaScript有一级函数的特性,也就是说,函数像其他值一样可以当成参数传来传去。

var result = [1,2,3].reduce(function(total, current){
    return total + current;
}, 0) //6;

使用箭头函数改造一下:

var result = [1,2,3].reduce((totoal, current) => total + current, 0);
console.log(result);

再看几个例子:

var even = [3,1,16,17,29].filter(el => !(el % 2));
console.log(even);
var sorted = data.sort((a, b) => {
    var diff = a.price - b.price;
    if(diff != 0){
        return diff;
   }
    return a.total - b.total;
})

1.1. 箭头函数的执行上下文

箭头函数有一个非常重要的特性,就是其执行上下文(也就是代码中的this)指向为外层代码,例如:

function MyComponent(){
    this.age = 26;
    setTimeout(() => {
      this.age += 1;
      console.log(this.age);
   }, 100);
}
new MyComponent(); // 27 in 100ms.

在Angular2中这一特性非常有用,对于特定的Component来说,箭头函数所绑定的上下文就是Component的实例。如果我们把MyComponent定义为Angular2中的组件,就可以使用age属性用来进行数据绑定。

原文地址:https://www.cnblogs.com/gavin-cn/p/6884411.html