【问题标题】:Why reference to constant before declaration does not throw?为什么在声明之前引用常量不会抛出?
【发布时间】:2021-01-15 11:37:39
【问题描述】:

为什么下面的代码不会在(*) 行抛出?

{
  function update() {
    console.log(this);
  }

  const THROTTLE_TIMEOUT = 1000;
  let throttled = false;

  function stopThrottling() {
    throttled = false;
  }

  function mouseMoveHandler(e) {
    if (throttled) return; throttled = true;
    setTimeout(stopThrottling, THROTTLE_TIMEOUT);

    update.call(Tracker); // (*)
  }

  //console.log(Tracker); // Throws

  const Tracker = {
    attached() {
      window.addEventListener('mousemove', mouseMoveHandler);
    }
  }

  Tracker.attached();
}

【问题讨论】:

  • 设置变量后调用该函数。在调试器中启动代码,您将看到它。

标签: javascript hoisting


【解决方案1】:

设置变量后调用函数。

变量Tracker设置在

//console.log(Tracker); // Throws

Tracker.attached();

线

update.call(Tracker);

之前没有被调用

Tracker.attached();

按照调试器中的程序流程或添加一些console.log 调试以查看它。

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多