ES6 块是否只能防止功能提升?
Are ES6 blocks only prevent function hoisting?
有人请帮我理解以下场景:
//Outer funtion
function foo() {
console.log('outer foo');
}
{
//Inner function
function foo() {
console.log('inner foo');
}
}
foo(); //Says "inner foo"
我假设在上述情况下,内部函数的显式减速会在块执行后替换提升的外部函数。
这是否意味着 ES6 块仅在内部声明时阻止函数提升?
更新
许多人认为这些块没有影响功能。但是,请根据 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
语句,在执行函数中的代码之前的函数初始扫描期间被提升到函数的顶部。
块与提升 var
语句或函数声明(两者都具有函数范围)无关。它们仅对具有块作用域的 let
和 const
重要。
有人请帮我理解以下场景:
//Outer funtion
function foo() {
console.log('outer foo');
}
{
//Inner function
function foo() {
console.log('inner foo');
}
}
foo(); //Says "inner foo"
我假设在上述情况下,内部函数的显式减速会在块执行后替换提升的外部函数。
这是否意味着 ES6 块仅在内部声明时阻止函数提升?
更新
许多人认为这些块没有影响功能。但是,请根据 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
语句,在执行函数中的代码之前的函数初始扫描期间被提升到函数的顶部。
块与提升 var
语句或函数声明(两者都具有函数范围)无关。它们仅对具有块作用域的 let
和 const
重要。