Javascript 作用域和提升到底发生了什么?
基于我当前的知识,我在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论