gpt4 book ai didi

javascript - 为什么函数被描述为 block 作用域

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:08 24 4
gpt4 key购买 nike

我正在阅读 this book on ES6并且有以下内容:

Function declarations…

  • are block-scoped, like let.
  • create properties in the global object (while in global scope), like var.
  • are hoisted: independently of where a function declaration is mentioned in its scope, it is always created at the beginning of the scope.

据我所知,函数一直是函数作用域。我认为 ES6 中可能发生了一些变化,但没有:

function a() {
if (true) {
// defined inside the block and is hoisted to the top of that block
z();
function z() { console.log ('z')}
}

z();
}

// but is also hoisted to the function scope
a(); // works OK

实际上,它们似乎是 block 范围的:

function a() {
if (false) {
// defined inside the block and is hoisted to the top of that block
z();
function z() { console.log ('z')}
}

z(); // error
}

那么它在 ES6 中有变化吗?

最佳答案

AFAIK, functions have always been function scoped. I thought something might have changed in ES6

确实如此:在 ES2015 之前,规范根本不涵盖 block 内声明的函数。支持它们是允许的扩展,但不是规范的一部分。

因此,规范必须克服重重困难,尤其是在浏览器的松散模式下。

strict 模式下,您会发现在兼容引擎上函数声明确实是 block 作用域的:

"use strict";

function test() {
if (true) {
function foo() {
console.log("foo called");
}
}
try {
foo(); // ReferenceError
} catch (e) {
console.log("Error: " + String(e));
}
}
test();

在兼容的 JavaScript 引擎上(例如任何最新版本的 Chrome 中的 V8,或任何最新版本的 Firefox 中的 SpiderMonkey),您将在上面得到一个 ReferenceError

关于javascript - 为什么函数被描述为 block 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41804038/

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