<分区>
MDN 说“函数声明的范围也限制在声明发生的 block 内”(link)并显示了一个示例:
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'
}
到目前为止一切顺利,但如果我们在其声明下调用函数:
{
function foo(location) {
console.log('foo is called ' + location);
}
foo('inside'); // works correctly and logs 'foo is called inside'
}
foo('outside'); // 'foo is called outside'
突然函数不再是 block 作用域,而是函数作用域。它的行为与 var 完全一样,后者是函数作用域:
console.log(typeof foo);//undefined
{
var foo = function(location) {
console.log('foo is called ' + location);
}
console.log(typeof foo);//function
}
console.log(typeof foo);//function
我的问题是:函数的范围是什么?如果它的范围是功能,那么提升有什么问题?或者它是正确的实现,但我没有正确理解某些内容?
由于一些困惑,我创建了以下示例: 1一切都很好
foo();//logs 'bar' because of hoisting
function foo(){
console.log('bar');
}
1b 一切正常,函数表达式没有提升
foo();//Error! foo is declared, so it was hoisted, but without its body, so it cannot be called
var foo = function(){
console.log('bar');
}
2 这会引起混淆。如果函数范围是函数,那么为什么下面的函数声明没有被提升?由于某些奇怪的原因,它像 1b 一样工作(函数表达式,而不是函数声明)
foo();//Error! foo is declared, so it was hoisted, but without its body, so it cannot be called
{
function foo(){
console.log('bar');
}
}
3 如果函数作用域是 block ,那么为什么函数在 block 外可用?
{
function foo(){
console.log('bar');
}
}
foo();//logs 'bar'
3b 一切都很好。让作用域为 block ,所以在 block 外不可用
{
let foo = function(){
console.log('bar');
}
}
foo();//Error, not declared