在JS中使用eval时,我遇到了奇怪的行为.
var f = function () { var x = 10; return function () { eval('console.log(x);'); window['eval']('console.log(x);'); } }; f()();
OUTPUT:
10 undefined:1 console.log(x); ^ ReferenceError: x is not defined
为什么使用eval显式捕获x但全局[‘eval’]没有?
即使全局[‘eval’]没有捕获x,为什么它在eval之后无法看到,它已经捕获了x?
解决方法
window [‘eval’]在全局范围内运行,eval()在本地范围内运行.
来自Mozilla的Javascript参考:
If you use the eval function indirectly,by invoking it via a
reference other than eval,as of ECMAScript 5 it works at global scope
rather than local scope; this means,for instance,that function
declarations create global functions,and that the code being
evaluated doesn’t have access to local variables within the scope
where it’s being called.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval