Javascript 作用域和提升到底发生了什么?

发布于 2025-01-18 03:34:10 字数 510 浏览 5 评论 0原文

基于我当前的知识,我在JavaScript中面临着真正出乎意料的事情。 考虑一下这个简单的代码:

foo();
if(true){
  function foo(){
    console.log(i);
  }
}
foo();

我知道,JS引擎将在创建阶段上将变量和功能声明悬挂。在此示例中,函数 foo 将被悬挂,当创建阶段完成时。引擎将开始按行运行代码,在代码的第一行中,应调用称为 foo 的函数。我们有该功能,因为它是在悬挂的吗?这个问题在这里是A typeerror 将被抛出,说 foo 不是一个函数。 当我删除时,如果块一切都很好。我认为这与块范围有点相关,但不知道它是如何确切和为什么这样的行为。

这是怎么回事?

我知道该功能声明不应放在块中。

Based on my current knowledge, I faced something really unexpected in Javascript.
Consider this simple code:

foo();
if(true){
  function foo(){
    console.log(i);
  }
}
foo();

I know that variable and function declarations will be hoisted by the Js engine at the creation phase. In this example the function foo will be hoisted and when creation phase is done. The engine will start to run the code line by line, at the first line of the code a function called foo should be invoked. We have that function, because it was hoisted before right? the problem is here a TypeError will be thrown which says that foo is not a function.
And when I remove the if block everything works well. I think it's somehow related to the block scopes but don't know how exactly and why it behaves like this.

What's going on here?

I know that function declarations should not be placed in blocks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文