ES6 箭头函数

解决的问题

1.缩减代码         2.改变this指向

 

1.缩减代码

ES5
const double = function(number){
  return number * 2  
}

ES6
const double = (number) => number * 2

2.改变this指向

ES5
const team1 = {
  members: ['Henry', 'Elyse'],
  teamName: 'es6',
  teamSummary: function(){
         return this.members.map(function(menber){
              return `${member}隶属于${this.teamName}小组`
         })
  }  
}

console.log(team1.teamSummary())         // ['Henry隶属于undefined小组', 'Elyse隶属于undefined小组']

分析:因为map方法中会改变this的指向,this不知道该指向谁


ES5
const team2 = {
  members: ['Henry', 'Elyse'],
  teamName: 'es6',
  teamSummary: function(){
         return this.members.map(function(menber){
              return `${member}隶属于${this.teamName}小组`
         }, bind(this))
  }  
}
console.log(team2.teamSummary())  // ['Henry隶属于es6小组', 'Elyse隶属于es6小组']

分析:bind可以将父级this的指向到map中

ES5
const team3 = {
  members: ['Henry', 'Elyse'],
  teamName: 'es6',
  teamSummary: function(){
        let that = this
         return this.members.map(function(menber){
              return `${member}隶属于${that.teamName}小组`
         })
  }  
}
console.log(team3.teamSummary())  // ['Henry隶属于es6小组', 'Elyse隶属于es6小组']

分析:将父级this赋值到that变量,在map中用that就相当于用this

ES6
const team4 = {
  members: ['Henry', 'Elyse'],
  teamName: 'es6',
  teamSummary: function(){
         return this.members.map((menber) =>{
              return `${member}隶属于${this.teamName}小组`
         })
  }
}
console.log(team4.teamSummary())  // ['Henry隶属于es6小组', 'Elyse隶属于es6小组']

分析: map中this的指向,是指向map函数父级的this

 

建议将以上代码在编辑器中运行查看,可以记忆比较深刻

posted @ 2019-07-31 15:36  小短腿奔跑吧  阅读(225)  评论(0编辑  收藏  举报