Search code examples
javascriptfunctionscopereferenceerror

JavaScript new Function scope ReferenceError


is there any way to make the code below working?

(function(){
    var n = "abc";
    (new Function("return alert(n);"))();
})();

If I run the code in browser result is: "Uncaught ReferenceError: n is not defined".

Also, I need to some other variables like "n" make accessible inside the "new Function" too.

Please help, Thank you


Solution

  • So you need to make that variables global.

    (function(){
        window.n = "abc";
        (new Function("return alert(n);"))();
    })();