js 权威指南函数章节中同一段代码在浏览器中可以执行, 但在 nodejs 下却无法执行?

在 <Javascript 权威指南> 书中的 8.7.7 节(大概在 213 页)中, 有以下代码

let scope = "global";
function constructFunction() {
    let scope = "local";
    return new Function(
        "return scope"
    );
}
// This line returns "global" because the function returned by the
// Function() constructor does not use the local scope.
constructFunction()();

在浏览器中正常执行并返回了预期的结果 global.
但在 nodejs 下却无法运行通过, 且会抛出异常 ReferenceError: scope is not defined.

请问, 这是为何?

阅读 1.8k
1 个回答

不同的原因是浏览器脚本中的顶级作用域是全局作用域,而 Node.js 文件中的顶级作用域是模块作用域。
你定义了 let scope = "global"; 在浏览器中顶层有windows对象,scope把挂在windows上,但是在 Node.js 模块范围内,var 只是在模块中创建一个 var,它不会在全局对象上创建全局或属性。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题