setTimeout + dom事件 中this指向问题

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
 <input type="text" id="input" />
</body>
</html>
function throttle(fn) {
  let canRun = true; // 通过闭包保存一个标记
  console.log('throttle',this);
  return function () {
         console.log('匿名函数',this);
        if (!canRun) return;
        canRun = false; 
    setTimeout(() => { 
          console.log('箭头函数',this);
          fn(arguments)
       
          canRun = true;
        }, 500);
      };
    }
    function sayHi(e) {
      console.log('sayHi-this',this)
      console.log('taget',e.target );
    }
const inputDom = document.querySelector('#input')

    inputDom.addEventListener('input', throttle(sayHi));

求教一个诡异的 this 指向问题,
第一点: fn() 调用时, 会转为this.fn(),
第二点: fn 是普通函数, 内部的 this 指向调用者, 所以内部的 this 指向 dom 才对,而实际上 this 指向了 window
第三点: 箭头函数的this, 始终和其外层第一个普通函数的this形成同步,所以当外层匿名函数的 this 变成 dom 对象时, , 箭头函数内的this 也变成dom,实际与这个理论一致,

综上, sayHi 函数中的 this, 应该指向 inputDom 才对啊, 为什么会是 window 呢

阅读 1.9k
2 个回答

只有第三点是对的。
一:我不知道你是从哪得出的fn调用时会转为this.fn,fn就是fn,你没有this.fn就不是this.fn,何来转一说
二:fn是普通函数,内部this指向的是全局也就是window

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题