gpt4 book ai didi

JavaScript 语法疯狂 : pointer to eval function is not the eval function?

转载 作者:行者123 更新时间:2023-11-29 16:15:59 27 4
gpt4 key购买 nike

以下需要在函数范围内,因为在交互式控制台模式下不会发生奇怪的行为。

以下函数按预期返回 5

(function() { var x = 5; return eval("x"); })()

一个简单透明的(ish)改变:

(function() { var x = 5; var j = eval; return j("x"); })()

产生错误:

ReferenceError: x is not defined

这是某种奇怪的安全措施吗?

最佳答案

您的第二个示例是对 eval间接调用。对 eval 的间接调用在全局范围内进行评估,其中 x 不可见:

var x = 10;

// This will return 10
(function() {
var x = 5;
var j = eval;
return j("x");
})();

// This will return 5
(function() {
var x = 5;
return eval("x");
})();

来自 the spec :

 1. ...if the eval code is not being evaluated by a direct call to the eval function then

     a. Initialize the execution context as if it was a global execution context...

关于JavaScript 语法疯狂 : pointer to eval function is not the eval function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15810844/

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