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