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

See code below. Why test2()is it causing an error, but test1()not? How to avoid an error (without overriding the called function inside the constructor)?

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"
                };
+4
source share
2 answers

I assume that all this is inside another function (maybe IIFE?). The code created with the help new Functionis evaluated in the global scope, and it seems that getRandomIntit is not available there.

Check out these demos on jsfiddle: it works if it is deployed , but not inside IIFE .

, eval:

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

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

+5

this MDN:

, Function, ; . , , Function. eval .

, getRandomInt ? jsFiddle .

+2

All Articles