gpt4 book ai didi

javascript - ES6 block 是否只能防止功能提升?

转载 作者:行者123 更新时间:2023-11-29 10:01:19 30 4
gpt4 key购买 nike

有人请帮助我理解以下场景:

//Outer funtion 
function foo() {
console.log('outer foo');
}

{
//Inner function
function foo() {
console.log('inner foo');
}
}

foo(); //Says "inner foo"

我假设在上述情况下,内部函数的显式减速会在 block 执行后替换提升的外部函数。

这是否意味着 ES6 block 仅在内部声明时防止函数提升?

更新

许多人认为这些 block 不会影响功能。但是,请根据 MDN 查看以下场景 -

foo('outside');  // TypeError: foo is not a function
{
function foo(location) {
console.log('foo is called ' + location);
}
foo('inside'); // works correctly and logs 'foo is called inside'
}

To be more precise, the block statement is preventing the function declaration from being hoisted to the top of the scope. The function is behaving as if it were defined as a function expression and, as such, it is only the implicit variable declaration that gets hoisted to the top of the scope

另一个更新

文档有误,只是由提供所选答案的专家修复。

最佳答案

I assume that in the above case the Inner function's explicit deceleration is replacing the hoisted outer function after the block is executed.

函数声明,如 var 语句,在执行函数中的代码之前,在函数的初始扫描期间被提升到函数的顶部。

block 与提升 var 语句或函数声明(两者都具有函数范围)无关。它们仅对具有 block 作用域的 letconst 重要。

关于javascript - ES6 block 是否只能防止功能提升?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56690249/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com