ES6箭头函数

前言:

近期使用箭头函数的过程中,偶尔有些混乱,故在此记录一下。

箭头函数

基本语法:

参数 => 函数体

基本用法:

var f = v => v;   等价于  var f = function(a){ return a; }
1. var f = (a,b) => a+b; //含有多个参数,参数区域用()括起来。
2. var f = () => console.log('Hello World!') //没有参数,参数区域用()括起来。
3. var f = (a,b) => { //函数体有多行语句时,函数体区域用{}包裹起来。
  let result = a+b;
  return result;
}
4. var f = v => v; //函数体只有一行语句,并且需要返回结果,可以省略{}.
5. var f = (id,name) => {(id:id,name:name)} //返回对象,对象需要用()包裹起来。

复杂例子:

const logger = store => next => action =>{
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  return result;
}


等价于

function logger(store){
  return function wrapDispatchToAddLogging(next){
      return function dispatchAndLog(action){
          console.log('dispatching', action)
          let result = next(action)
          console.log('next state', store.getState())
          return result;
      }
  }  
}

NOTE:箭头函数没有this、super、arguments和new.target绑定

var func = () => {
  // 箭头函数里面没有 this 对象,
  // 此时的 this 是外层的 this 对象,即 Window 
  console.log(this)
}
原文地址:https://www.cnblogs.com/zouyanzhi/p/12759099.html