arrow function

本篇文章是es6学习笔记,将github上的文章翻译并整理一下;

箭头函数在许多现在语言中都已经支持了,javascript在es6当中也终于支持了

  • 下面的代码段,我们用一个参数,返回了一个结果

[1,2,3].map( num=> num * 2 ) 
// <- [2,4,6]

用es5表示

[1, 2, 3].map(function (num) { return num * 2 })
// <- [2, 4, 6]

  • 如果我们需要用到更多的参数,或者不用参数,那么我们需要圆括号将参数包裹起来.

[1,2,3].map(( num,index ) => num*2+index )
//<-[2,5,8,11]

  • 当需要其他代码块,并且只返回一个表达式时我们需要中括号

[1,2,3,4].map(num => {
    var multiplier = 2 + num;
    return num * multiplier
})
// <- [3, 8, 15, 24]

  • 当你运用插入语法时,你也可以添加更多参数

[1, 2, 3, 4].map((num, index) => {
  var multiplier = 2 + index
  return num * multiplier
})
// <- [2, 6, 12, 20]

  • 当我们需要返回一个对象的时候我们需要把表达式包裹在大括号中,只有这样才不会被解析成代码块

[1, 2, 3].map(n => { number: n })
// [undefined, undefined, undefined]

[1, 2, 3].map(n => { number: n, something: 'else' })
// <- SyntaxError

[1, 2, 3].map(n => ({ number: n }))
// <- [{ number: 1 }, { number: 2 }, { number: 3 }]

[1, 2, 3].map(n => ({ number: n, something: 'else' }))
/* <- [
  { number: 1, something: 'else' },
  { number: 2, something: 'else' },
  { number: 3, something: 'else' }]
*/

  • 一个很酷的属性是箭头函数绑定了this上下文的属性

function Timer () {
  this.seconds = 0
  setInterval(() => this.seconds++, 1000)
}
var timer = new Timer()
setTimeout(() => console.log(timer.seconds), 3100)
// <- 3


你可能感兴趣的:(arrow function)