1,833   JS

近几年 JS 为了适应时代发展,推出了许多新规范,ECMAScript 6 出现了箭头函数

 

一,来看看实例

    // 以往的写法
    $("#button").click(function () {
         dosomething();
    });
    // 箭头函数
    $("#button").click( () => {
         dosomething();
    });

 

第一感觉就是简洁了好多

如果只是为了简洁而提出这样的语法糖,总觉得有点大题小作了;

 

二,箭头函数还有另外一个特点,它没有自己的this值,箭头函数内的this值继承自外围作用域;

 

这个好处在哪里呢?在多层嵌套的函数了, 可能出现多个 this ,容易混乱,为了获得对应的 this,还得另外指定一个 self 变量来保存当前对象的 this ;

看看 Mozilla 的例子

 

// 以往的写法
function Person() {
  var self = this; // 使用 `self` 保存当前对象 
  self.age = 0;

  setInterval(function growUp() {
    // 回调里面的 `self` 变量就指向了期望的那个对象了
    self.age++;
  }, 1000);
}


// 箭头函数
function Person(){
  this.age = 0;

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

 

是不是又感觉瞬间舒爽了,哈哈,箭头函数的好处慢慢在代码使用中感受吧




Trackbacks/Pingbacks

  1.  this.setState is not a function | LuckyBird

Leave a Reply

Your email address will not be published. Required fields are marked *