箭头函数this的问题

箭头函数没有自己的this对象

箭头函数没有自己的this对象,所以在箭头函数取this的时候就是定义时上层作用域中的this

function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

var id = 21;
//foo() 21 这时候foo的this指向window
foo.call({ id: 42 })//42 foo的this指向{ id: 42 }

并且箭头函数时向上找最近的定义时上层作用域

 var id = 21;

      function foo() {
        return () => {
          return () => {
            console.log("id1:", this.id);
            return function () {
              return () => {
                console.log("id:", this.id);
              };
            };
          };
        };
      }
      var f = foo.call({id: 1}); //this 指向{id: 1}
      var t1 = f.call({id: 2})(); //1 这时候修改箭头函数的this生效
      t1()(); //id 为21 因为匿名函数的this指向window
原文地址:https://www.cnblogs.com/heihei-haha/p/14789525.html