请参阅下面的代码。 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"
};
答案 0 :(得分:5)
我假设所有内容都在另一个函数内(IIFE,也许?)。使用new Function
创建的代码在全局范围内进行评估,似乎getRandomInt
不可用。
在jsfiddle上检查这些演示:it works if unwrapped,but not inside an IIFE。
如果您需要在当前范围内评估代码,则必须使用eval
:
var test2 = eval('(function(){return getRandomInt(10, 20);})');
答案 1 :(得分:2)
我在MDN上找到了this:
使用Function构造函数创建的函数不会创建闭包 他们的创作背景;它们总是在全球范围内创造的 范围。在运行它们时,它们只能访问自己的 局部变量和全局变量,而不是来自范围的变量 调用了Function构造函数。这与使用eval不同 使用函数表达式的代码。
那么也许你的getRandomInt
不在全球范围内?需要查看整个代码,或者jsFiddle重新创建问题。