ES6的箭头函数

166 阅读1分钟

ES6添加了箭头函数

表达式模式:

ES6

odds  = evens.map(v => v + 1)
pairs = evens.map(v => ({ even: v, odd: v + 1 }))
nums  = evens.map((v, i) => v + i)

ES5

odds  = evens.map(function (v) { return v + 1; });
pairs = evens.map(function (v) { return { even: v, odd: v + 1 }; });
nums  = evens.map(function (v, i) { return v + i; });

这种模式=>后跟的是一个表达式,也就是函数的返回值。

声明体模式:

ES6

nums.forEach(v => {
   if (v % 5 === 0)
       fives.push(v)
})

ES5

nums.forEach(function (v) {
   if (v % 5 === 0)
       fives.push(v);
});

这种模式=>后跟的是块级声明{},里面是函数体。

还有一点不同是this的指向,在箭头函数里this是指向其上级函数里的this,例如:

ES6

this.nums.forEach((v) => {
    if (v % 5 === 0)
        this.fives.push(v)
})

ES5

var self = this;
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        self.fives.push(v);
});