为什么使用函数构造函数创建的 Javascript 函数无法访问在其外部定义的其他函数

Why is a Javascript function created with Function constructor unable to access other functions defined outside of it?

本文关键字:函数 访问 外部 其他 定义 Javascript 构造函数 创建 为什么      更新时间:2023-09-26

请参阅下面的代码。为什么test2()会导致错误,而test1()不会?如何避免错误(无需在构造函数中重新定义被调用的函数)?

function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
var xyz = function (){
                var test1 = function () { getRandomInt(10, 20); };
                test1();  // runs with out problem 
                var test2 = new Function('getRandomInt(10, 20);');
                test2(); //results in "Uncaught ReferenceError: getRandomInt is not defined"
                };

我假设所有这一切都在另一个函数中(也许是 IIFE?使用 new Function 创建的代码在全局范围内进行评估,似乎getRandomInt在那里不可用。

在 jsfiddle 上检查这些演示:如果解开包装,它可以工作,但在 IIFE 中不起作用。

如果需要在当前范围内评估代码,则必须使用 eval

var test2 = eval('(function(){return getRandomInt(10, 20);})');

http://jsfiddle.net/7wPK4/2/

引用

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
  • http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.2.1

我在MDN上找到了这个:

使用函数构造函数创建的函数不会创建闭包 到他们的创作背景;它们始终是在全球创建的 范围。运行它们时,它们只能访问自己的 局部变量和全局变量,而不是来自 调用了函数构造函数。这与使用 eval 不同 使用函数表达式的代码。

所以也许你的getRandomInt不在全球范围内?需要查看整个代码,或者 jsFiddle 重新创建问题。