Cannot find variable in a simple function inside a for of loop (safari)

喜你入骨 提交于 2020-01-25 00:20:28

问题


I'm trying to discover why Safari returns a console error whereas other browsers like Chrome have no problem. There is a simple function inside a for of loop as follows:

const links = document.querySelectorAll('ul > li > a');

console.log(links); // successful

for (const link of links) {
    console.log(link); // successful
  
  function logLink() {
    console.log(link);
  }
  
  logLink();
}
<ul id='test'>
  <li>
    <a class='one' href='#'>test 1</a>
  </li>
  <li>
    <a class='two' href='#'>test 2</a>
  </li>
  <li>
    <a class='three' href='#'>test 3</a>
  </li>
</ul>

Codepen: https://codepen.io/ns91/pen/oNNEKpP

Open the above codeine URL in safari and open your javascript console. As you can see, in Safari, the function logLink(); doesn't seem to log the link variable, although it works in Chrome.

The error I'm getting is: ReferenceError: Can't find variable: link

Does anyone know why this is happening, and how to fix it?

Thanks for any help here.


回答1:


Function declarations are scoped to the function they are declared inside and hoisted (so it is outside the for loop's block) but const declarations are scoped to the containing block.

link only exists inside the block, logLink lives outside it, so logLink doesn't have access to the link constant.

Use a function expression and a const so the function is scoped to the for loop's block like the link constant.

const links = document.querySelectorAll('ul > li > a');
for (const link of links) {
  const logLink = function logLink() {
    console.log(link);
  }
  logLink();
}
<ul id='test'>
  <li>
    <a class='one' href='#'>test 1</a>
  </li>
  <li>
    <a class='two' href='#'>test 2</a>
  </li>
  <li>
    <a class='three' href='#'>test 3</a>
  </li>
</ul>


来源:https://stackoverflow.com/questions/58708552/cannot-find-variable-in-a-simple-function-inside-a-for-of-loop-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!