首页 > 其他 > 详细

ES6箭头函数

时间:2017-10-25 10:23:52      阅读:213      评论:0      收藏:0      [点我收藏+]

ES6 中,箭头函数就是函数的一种简写形式,使用括号包裹参数,跟随一个 =>,紧接着是函数体:

var getPrice = function() {
  return 4.55;
};

// Implementation with Arrow Function
var getPrice = () => 4.55;

需要注意的是,上面栗子中的 getPrice 箭头函数采用了简洁函数体,它不需要 reture 语句,下面这个栗子使用的是正常函数体:

var materials = [
  ‘Hydrogen‘,
  ‘Helium‘,
  ‘Lithium‘,
  ‘Beryllium‘
];

materials.map(function(material) { 
  return material.length; 
}); // [8, 6, 7, 9]

materials.map((material) => {
  return material.length;
}); // [8, 6, 7, 9]

materials.map(material => material.length); // [8, 6, 7, 9]

当然,箭头函数不仅仅是让代码变得简洁,函数中 this 总是绑定总是指向对象自身。具体可以看看下面几个栗子:

我们经常需要使用一个变量来保存 this,然后在 growUp 函数中引用:

function Person() {
  var self = this;
  self.age = 0;

  setInterval(function growUp() {
    self.age++;
  }, 1000);
}
var person = new Person();

An arrow function does not have its own this; the this value of the enclosing execution context is used. Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the enclosing function:

function Person(){
  this.age = 0;

  setInterval(() => {
    // |this| 指向 person 对象
    this.age++;
  }, 1000);
}

var person = new Person();

 

ES6箭头函数

原文:http://www.cnblogs.com/wujiaqi/p/7727297.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!