下面的代码应该工作吗?
if(true) {
async function bar() {
console.log("hello");
}
}
bar();
Chrome 80 和 Firefox 72 都抛出
ReferenceError
说bar
没有定义。所以看起来像 async function bar() {...}
声明是 block 范围的,而 function bar() {...}
声明是函数范围的?如果是这种情况令人困惑,但是有人可以通过指向规范相关部分的链接为我确认吗?另外,有没有办法制作
async function
从 block 内声明时声明函数范围?
最佳答案
It seems like
async function bar() {...}
declarations are block scoped
是的,就像平常一样。函数声明通常是 block 范围的。
… whereas
function bar() {...}
declarations are function scoped?
不是,except in sloppy mode for legacy reasons .这不影响
async function
和 function*
声明,不需要任何向后兼容性。
关于javascript - `function` 声明是函数范围的,但 `async function` 声明是 block 范围的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60376197/