ES6-对箭头函数的理解与使用细节

箭头函数,要注意一点其本身不指定作用域;

Test() {
  let that = this;
  this.data.name = "安";
  let inner = {
    func: (peram) = >{
      this.name = "旭"
    },
    func1: function() {
      this.name = "安旭"
    }
  }
  inner.func();
  inner.func1();
  console.log("~~~~~~~~~~~~~~~~1~~~~~~~~~~~~~~~~~~", this.name)
  // 输出: ~~~~~~~~~~~~~~~~1~~~~~~~~~~~~~~~~~~ 旭
}

1、为什么会输出 ‘ 旭 ’
因为 ES6 中的箭头函数,不指定作用域,他的作用域就是上一级(一级一级的往上找)的作用域;
而function(){}, 创建自己的作用域;
2、建议使用赋值 that 吗?
因人而异,一种情况就是,在 () => {} 存在过多时,如果不使用赋值 that,担心会迷;
3、是否要用箭头函数全部替代 function函数?
在需要闭合环境下,不适用箭头函数,而是使用 function 函数;

多交流。。。

发布了19 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/an_xinyu/article/details/80423882