ES6 箭头函数中this指向问题

【this一般指向自身所处函数的调用者】

箭头函数自身不具备this,箭头函数中的this等于定义箭头函数位置的this

  let obj = {
    name: "James"
  };

  function funcThisTest() {
    console.log(this);
    return function () {
      console.log(this);
    }
  }

  let f = funcThisTest.call(obj); // 返回Object obj
  f(); // 返回window对象

倘若使用箭头函数应为:

  let obj = {
    name: "James"
  };

  function funcThisTest() {
    console.log(this);
    return () => console.log(this);
  }

  let f = funcThisTest.call(obj); // Object obj
  f(); // Object obj

 加深印象:

对象中this指向window对象,由此易知下面代码中thisTest【箭头函数】中this指向的其实就是window对象,

而普通函数中this指向函数的调用者,也就是obj对象

  let obj = {
    name: "James",
    that: this,
    thisTest: () => {
      console.log(this);
    },
    thisTest_() {
      console.log(this);
    }
  };
  obj.thisTest(); // window
  obj.thisTest_(); // obj
  console.log(obj.that); // window

 

posted @ 2021-08-09 17:18  TwinkleG  Views(55)  Comments(0)    收藏  举报