我有以下两个小脚本:
脚本 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 = 3
或 local = 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/