箭头函数的 this 绑定定义时所在的作用域

箭头函数转成 ES5 的代码如下。

  1. // ES6
  2. function foo() {
  3. setTimeout(() => {
  4. console.log('id:', this.id);
  5. }, 100);
  6. }
  1. // ES5
  2. function foo() {
  3. var _this = this;
  4. setTimeout(function () {
  5. console.log('id:', _this.id);
  6. }, 100);
  7. }

不适用场合

  • 由于箭头函数使得this从“动态”变成“静态”,下面两个场合不应该使用箭头函数。

    • 第一个场合是定义对象的方法,且该方法内部包括this。
      1. const cat = {
      2. lives: 9,
      3. jumps: () => {
      4. this.lives--;
      5. }
      6. }
  • cat.jumps() 方法是一个箭头函数,这是错误的。调用 cat.jumps() 时,如果是普通函数,该方法内部的 this 指向 cat;如果写成上面那样的箭头函数,使得 this 指向全局对象,因此不会得到预期结果。这是因为对象不构成单独的作用域,导致 jumps 箭头函数定义时的作用域就是全局作用域。

    • 第二个场合是需要动态 this 的时候,也不应使用箭头函数。
      1. var button = document.getElementById('press');
      2. button.addEventListener('click', () => {
      3. this.classList.toggle('on');
      4. });
  • 上面代码运行时,点击按钮会报错,因为 button 的监听函数是一个箭头函数,导致里面的 this 就是全局对象。如果改成普通函数,this 就会动态指向被点击的按钮对象。


}


  • }
    }