gpt4 book ai didi

Javascript变量捕获

转载 作者:数据小太阳 更新时间:2023-10-29 04:33:18 26 4
gpt4 key购买 nike

我在 JS 中使用 eval 时遇到了奇怪的行为。

var f = function () {
var x = 10;

return function () {
eval('console.log(x);');
window['eval']('console.log(x);');
}
};

f()();

输出:

10
undefined:1
console.log(x);
^
ReferenceError: x is not defined

为什么使用 eval 显式捕获 xglobal['eval'] 却没有?即使 global['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

关于Javascript变量捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39551208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com