javascript - JSFiddle 中的可变作用域行为

标签 javascript function global-variables eval

我有以下两个小脚本:

脚本 1:

eval("local = 3;");
console.log(typeof local);
Function("console.log(typeof local);")();

输出:

number
number

脚本 2:

eval("var local = 3;");
console.log(typeof local);
Function("console.log(typeof local);")();

输出:

number
undefined

什么给了? eval 是否应该将 local 放在全局命名空间中,而不管传递的字符串是否具有 var local = 3local = 3?如果是这样的话,Function(...) 不应该在第二种情况下发现 local 的类型是 number 而不是 undefined 吗?

编辑 1:

我在 JSFiddle 中运行了这两个脚本,这就是我得到的结果。但是,当我在 JSFiddle 之外运行它们时,预期的结果出现在两个输出的位置:

number 
number

最佳答案

来自 MDN :

Functions created with the Function constructor do not create closures to their creation contexts; they always run in the window context (unless the function body starts with a "use strict"; statement, in which case the context is undefined).

就规范而言,这是因为 15.3.2.1 中的步骤 11 (强调我的):

Return a new Function object created as specified in 13.2 passing P as the FormalParameterListopt and body as the FunctionBody. Pass in the Global Environment as the Scope parameter and strict as the Strict flag.

因此您的脚本 2 在本地范围内创建了一个变量(which I'm assuming is not global,否则输出将不同1),并且 console.log 已被评估通过 Function 看不到它。


1 正如您的评论所证实的那样,您在 jsfiddle 中运行测试,默认情况下它会将您的代码包装在 window.onload 处理程序中,迫使您离开全局范围。

关于javascript - JSFiddle 中的可变作用域行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18025004/

相关文章:

objective-c - 编译器错误 : "initializer element is not a compile-time constant"

javascript - 在单个 JavaScript 函数中可以对 DOM 进行多少次更改是否有限制?

javascript - HTML,当我聚焦时显示每个文本框的 ID

asp.net - RadioButtonList 的 SelectedIndexChange 上的 JavaScript "confirm"

javascript - Uncaught ReferenceError : Meteor is not defined

python - Python 中的全局变量和局部变量

javascript - 简单的自定义 JavaScript 滚动条

c++ - 是否可以使函数在 C++ 中返回类型名?

php - 如何删除 WooCommerce 订单状态?

java - 如何增加 if 语句中的变量以便在另一个语句中使用?