ES6 - 箭头函数

/**
 * 1.箭头函数语法
 */
const double1 = function (number) {
  return number * 10;
}

const double2 = (number) => {
  return number * 20;
}

const double3 = (number) => number * 30;

console.log(double1(2)); //20
console.log(double2(2)); //40
console.log(double3(2)); //60

var sum = (num1, num2) => num1 + num2;
//	有效等价于:
// var	sum	=	function(num1,	num2)	{
// 				return	num1	+	num2;
// };

var getTempItem = id => ({ id: id, name: "Temp" });
//	有效等价于:
// var	getTempItem	=	function(id)	{
//   return	{
//           id:	id,
//           name:	"Temp"
//   };
// };

/**
 * 2.箭头函数改变this指向
 */

 /**
  * 2.1 self方法
  */
const team1 = {
  members: ["Henry", "Elyse"],
  teamName: "es6",
  teamSummary: function () {
    let self = this;
    return this.members.map(function(member) {
      // this不知道该指向谁了
      return ` ${member}隶属于${self.teamName}小组`;
    })
  }
}

/**
 * 2.2 bind 硬编码
 */
const team2 = {
  members: ["Henry", "Elyse"],
  teamName: "es6",
  teamSummary: function () {
    return this.members.map(function(member) {
      // this不知道该指向谁了
      return ` ${member}隶属于${this.teamName}小组`;
    }.bind(this))
  }
}

/**
 * 2.3 箭头函数
 */
const team3 = {
  members: ["Henry", "Elyse"],
  teamName: "es6",
  teamSummary: function () {
    let self = this;
    return this.members.map((member) => {
      return ` ${member}隶属于${this.teamName}小组`;
    })
  }
}

console.log(team1.teamSummary()); //[" Henry隶属于es6小组", " Elyse隶属于es6小组"]
console.log(team2.teamSummary()); //[" Henry隶属于es6小组", " Elyse隶属于es6小组"]
console.log(team3.teamSummary()); //[" Henry隶属于es6小组", " Elyse隶属于es6小组"]

posted @ 2019-12-04 23:32  【唐】三三  阅读(140)  评论(0编辑  收藏  举报